#!/usr/bin/wish -f
#
# Copyright (c) 2020 NVI, Inc.
#
# This file is part of VLBI Field System
# (see http://github.com/nvi-inc/fs).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# Screen layout constants

# Determine the resolution. 
  set win_sizeX [winfo screenwidth .]
  set win_sizeY [winfo screenheight .]  
  wm geometry . +0+0
 
#position window full screen from top left corner.
if {$win_sizeX <= 1024 || $win_sizeY <= 768} {
    set size 2.5  ;# Multiplication factor to change size of plotting area
} else {
    set size 3    ;# Multipication factor to change size of plotting area
}

set mainTitleText "Gain Plot"
set CurrentProgramVersion 1
set CurrentProgramRelease 1
set CurrentProgramBuild 4

set current_DefaultDir "/usr2/log"
set newfile_filename ""
set statusMessage "Please open a FS log file."
set text_title_print "Print plot"
set text_title_preferences "I/O setup"
set text_printing_wait "Printing, please wait..."
set text_ready "Ready."
set text_replot "Replotting needed"
set text_zero "Upper and lower limits equal. Check selection, reset the plot (Press 's'), or scale manually."

set print_default_filename "postscript.eps"
set print_destination 0    ;# 0=Printer, 1=File
set print_command 0        ;# 0=lpr, 1=psprint

set xoffset 80 
set xrightoffset 60
set yoffset 50
set yrightoffset 45
set pointoffplot 4
set ytitleoffset 15
set pointsize 3
set decimals 3
set thickline 3        ;#The line width for curves in working files


set BADVALUE -6000000    ;#gndats definition of a "bad" number
set BADSTRVALUE X        ;#gndats definition of a "bad" string


set pid [pid]

set controlFileDir "/usr2/control/rxg_files"     ;#Default directory for control files   
set currentInputFitFile "/tmp/input.fit.$pid"    ;#Input file to gnfit
set currentOutputFitFile "/tmp/output.fit.$pid"  ;#Output file from gnfit
set current_TEMP  "/tmp/gnplt.tmp.$pid"          ;#Temporary file used by the printing procedures
set currentRXG ""                                ;#The current .rxg file, is set later
set tempRXG "$controlFileDir\/tmp.rxg.$pid"         ;#A temporary .rxg file, used for I/O with .rxg files
set currentOutputFile "/tmp/parsed.txt.$pid"     ;#Output file from gndat
set newfile_filename ""                          ;#The log file that the user selects

set sourcelist {}        ;#a list of all sources in the datafile
set detectorlist {}      ;#a list of all detectors in the datafile
set leftfreqlist {}      ;#a list of all left pol frequencies in the datafile
set rightfreqlist {}     ;#a list of all right pol frequencies in the datafile
set leftfreqLabellist {} ;#a list of the detectors corresponding to the frequencies
set rightfreqLabellist {};#a list of the detectors corresponding to the frequencies
set timelist {}          ;#a list of all times in the datafile
set editedlist {}        ;#a list of the RXG files which have been updated
set LOFilelist {}        ;#a list of all the RXG files
set scaling Auto         ;#sets autoscaling as default
set hasScaled -1         ;#makes the manual scaling window appear only once
set SDmenus_is_set 0     ;#makes the source and detector menus be set only once
set writeflag 0          ;#have the .rxg files been updated? 0=No ; 1=yes
set opacityCorrect 0     ;#flag determining if the gain should be corrected for opacities
set opacityFlag 0        ;#flag determining whether the gain has been opacity corrected or not
set hourint 1            ;#the time interval for fitting trec and tau0 
set autoreplot 0         ;#replots automatically when the user selects different axes, 0=No ; 1=Yes
set autoStyle 0          ;#determines which type of autoscaling to use
set pointsSelected 0     ;#Number of points selected.
set pointsHighlighted 0  ;#Number of points highlighted
set pointsDeleted 0      ;#Number of points deleted.
set pointsIncluded 0     ;#Number of points included.
set number_of_datalines 0 ;#Number of input data
#MC:AO added when modified the procedures printTCalToRXG and fitForTCal
set calTableFrequency {}
set calTableTemperature {}
set TCAL_TABLE_ENDER "end_tcal_table"
# end MC:AO

set currentPol ""

#These are the items of the X-axis and the Y-axis. 
set xitemlist {"Time" "Elevation" "Frequency" "Azimuth" "Airmass"} 
set yitemlist {"Azimuth" "Elevation" "Gain Compression" "Tsys" "SEFD" "TCal(Jy)" "TCal(K)" "TCal Ratio" "Tsys-Tspill"}

set letteroffset 3       ;#scale factor for how far from points source letters are displayed
set sourcedisplay 2      ;#1=source letters are displayed, 0=points are diplayed, 2=both are displayed

set sourceLetterList {A B C D E F G H I J K L M N O P Q R S T U V W X Y Z} ;#allows for 26 sources to be plotted. 
		                                                           ;#Add more letters if necessary        
set sourceColourList {black blue2 tomato2 chocolate cyan azure4 brown1 \
	DeepSkyBlue ForestGreen violet HotPink LawnGreen orange3 burlywood \
	PeachPuff4 orchid4 magenta2 khaki4 DarkGrey DarkSalmon firebrick \
	gold GreenYellow PapayaWhip RoyalBlue1 wheat4}

set lowerGC 0.95 ;#Default lower limit for "bad" Gain Compression
set upperGC 1.05 ;#Default upper limit for "bad" Gain Compression
set tatm 273     ;#Default value for Tatm

set XPointLabel ""
set YPointLabel ""

# ==========================================================================
#
#                              DATA SECTION
#
# ==========================================================================

# -----------------------------------------------------------------------------------------------
# This procedure displays the file selection window to the user. It also resets all the lists and
# menus that are used.
# -----------------------------------------------------------------------------------------------

proc fileselection_dialog {} {
    global global_startmode current_DefaultDir newfile_filename currentOutputFile SDmenus_is_set legendNo header
    global sourcelist detectorlist timelist leftfreqlist rightfreqlist leftfreqLabellist rightfreqLabellist 
    global LONamelist LOTypelist LOFirstlist LOSecondlist statusMessage controlFileDir
    global LOFilelist editedlist
    set types {
	{{Log Files} {*.log} }
	{{All Files} {*.*} }
    }
    set newfile_filename [tk_getOpenFile -title "Open new FS log file" -filetypes $types -initialdir \
	    $current_DefaultDir]
    if {$newfile_filename != ""} {
	set sourcelist {}        ;#a list of all sources in the datafile
	set detectorlist {}      ;#a list of all detectors in the datafile
	set timelist {}          ;#a list of all times in the datafile
	set leftfreqlist {}      ;#a list of all left pol frequencies in the datafile
	set rightfreqlist {}     ;#a list of all right pol frequencies in the datafile
	set leftfreqLabellist {} ;#a list of the detectors corresponding to the frequencies
	set rightfreqLabellist {};#a list of the detectors corresponding to the frequencies
	set LONamelist {}        ;#a list of the names of the LOs
	set LOFilelist {}        ;#a list of the names of the .rxg files
	set LOTypelist {}        ;#a list of the type of the LOs (range or fixed)
	set LOFirstlist {}       ;#a list of the LO frequencies (start freq. for range)
	set LOSecondlist {}      ;#a list of the LO frequencies (end freq. for range)
	set editedlist {}        ;#a list of the RXG files which have been updated
	set legendNo 1           ;#makes the source legend be set only once
	set header ""
	destroy .menuBar.source.menu
	destroy .menuBar.frequ.menu
	destroy .menuBar.edit.menu
	menu .menuBar.source.menu
	menu .menuBar.frequ.menu
	menu .menuBar.edit.menu
	set SDmenus_is_set 0
	set currentOutputFile [exec gndat $newfile_filename $currentOutputFile 0 $controlFileDir]
	if {$currentOutputFile==-1} {
	    set statusMessage "There's a problem with the .rxg files. Please check the $controlFileDir directory"
	    update
	} else {
	    .c delete points
	    .c delete sourcetext
	    .c itemconfigure opacityHeader -text ""
	    clearScreen
	    readData $currentOutputFile
	}
    } else {
	if {![info exists number_of_datalines]} {
	    set statusMessage "Please try opening a file again."
	}
    }
}

# ----------------------------------------------------------------------------------------------------
# This procedure recieves a file name where the parsed data is. Default:/tmp/parsed.txt. It then reads
# the data storing it in a dataMatrix. The columns are the different items, and the rows are each 
# observation. It also reads the LO information and sets up the items menus.
# ----------------------------------------------------------------------------------------------------

proc readData filename {
    global dataMatrix xitem items timeinseconds number_of_datalines statusMessage
    global leftfreqlist rightfreqlist leftfreqLabellist rightfreqLabellist SDmenus_is_set legendNo sourcelist
    global detectorlist timelist LONamelist LOTypelist LOFirstlist LOSecondlist LOFilelist text_replot text_ready
    global opacityCorrect pid replot autoreplot scaling hasScaled yitemlist maxvalue
    set LONamelist {}        ;#a list of the names of the LOs
    set LOFilelist {}        ;#a list of the names of the .rxg files
    set LOTypelist {}        ;#a list of the type of the LOs (range or fixed)
    set LOFirstlist {}       ;#a list of the LO frequencies (start freq. for range)
    set LOSecondlist {}      ;#a list of the LO frequencies (end freq. for range)
    set statusMessage "Reading log file..."
    update
    set number_of_labels 0
    set number_of_datalines 0
    set number_of_datacolumns 0
    destroy .menuBar.items.menu
    menu .menuBar.items.menu
    set fileID [open $filename r]
    ;#set i 0
    set header ""
    while {[gets $fileID line] > 0} {
	;#set number_of_datacolumns 0
	if {[string index $line 0] != "\*"} {
	    if {[string index $line 0] == "\$"} {
		set header [string range $line 1 end]
	    } else {
		if {$header == "DPFU"} {
		    set dpfulist $line
		    split $dpfulist
		}
		if {$header == "GAIN"} {
		    set gainlist $line
		    split $gainlist
		}
		if {$header == "LABELS"} {
		    lappend labellist $line
		    if {[lsearch $yitemlist $line]!=-1} {
		        if {$number_of_labels > 0} {
		            ;#set label$number_of_labels $line
		            .menuBar.items.menu add radiobutton -label "$line" -variable items \
		            -value [lindex $labellist $number_of_labels] -command {
		                set statusMessage "Replotting needed"
		                set gainChoice 0
		                set assChoice 0
		                set scaling Auto
		                set hasScaled 0
		                if {$autoreplot==1} {
		                    replot
		                }
		            }
		        }
		    }
		    incr number_of_labels   
		}
		if {$header == "DATA"} {
		    incr number_of_datalines
		    set datalist $line
		    split $datalist
		    foreach column $datalist {
		        set dataMatrix($number_of_datalines,[lindex $labellist $number_of_datacolumns]) $column
		        incr number_of_datacolumns
		    }
		    set number_of_datacolumns 0
		}
		if {$header == "LO"} {
		    incr number_of_datalines -1
		    split $line
		    set name [lindex $line 0]
		    lappend LOFilelist [lindex $line 0]
		    lappend LOTypelist [lindex $line 1]
		    lappend LOFirstlist [lindex $line 2]
		    lappend LOSecondlist [lindex $line 3]
		    lappend LONamelist [lindex [split [lindex [split $name /] end] .] 0]
		    ;#incr i
		}
	    }
	}
    }
    .menuBar.items.menu add separator
    .menuBar.items.menu add cascade -label "Assumed Items" -menu .menuBar.items.menu.ass
    menu .menuBar.items.menu.ass
    .menuBar.items.menu.ass add radiobutton -label "TCal(K)" -variable assChoice \
	    -value 1 -command {
	set statusMessage $text_replot
	set items "Assumed TCal(K)"
	if {$autoreplot==1} {
	    replot
	}
    }
    .menuBar.items.menu.ass add radiobutton -label "Source Flux" -variable assChoice \
	    -value 2 -command {
	set statusMessage $text_replot
	set items "Assumed Source Flux"
	if {$autoreplot==1} {
	    replot
	}
    }
    .menuBar.items.menu.ass add radiobutton -label "DPFU" -variable assChoice \
	    -value 3 -command {
	set statusMessage $text_replot
	set items "Assumed DPFU"
	if {$autoreplot==1} {
	    replot
	}
    }
    .menuBar.items.menu.ass add radiobutton -label "Gain Curve" -variable assChoice \
	    -value 4 -command {
	set statusMessage $text_replot
	set items "Assumed Gain Curve"
	if {$autoreplot==1} {
	    replot
	}
    }
    .menuBar.items.menu.ass add radiobutton -label "DPFU*Gain Curve" -variable assChoice \
	    -value 5 -command {
	set statusMessage $text_replot
	set items "Assumed DPFU*Gain Curve"
	if {$autoreplot==1} {
	    replot
	}
    }
    .menuBar.items.menu add separator
    .menuBar.items.menu add cascade -label "Gain" -menu .menuBar.items.menu.gain
    menu .menuBar.items.menu.gain
    .menuBar.items.menu.gain add radiobutton -label "TCal(K) from working file" -variable gainChoice \
	    -value 1 -command {
	set statusMessage $text_replot
	set items "Gain"
	tcalkFrom $gainChoice
	correctForOpacities
	if {$autoreplot==1} {
	    replot
	}
    }
    .menuBar.items.menu.gain add radiobutton -label "TCal(K) from user input" -variable gainChoice \
	    -value 2 -command {
	set statusMessage $text_replot
	set items "Gain"
	tcalkFrom $gainChoice
	correctForOpacities
	if {$autoreplot==1} {
	    replot
	}
    }
    .menuBar.items.menu.gain add radiobutton -label "Specify gain for elev. range" -variable gainChoice \
	    -value 3 -command {
	set statusMessage $text_replot
	set items "Gain"
	tcalkFrom $gainChoice
	correctForOpacities
	if {$autoreplot==1} {
	    replot
	}
    }
    .menuBar.items.menu.gain add cascade -label "Correction" -menu .menuBar.items.menu.gain.opac
    menu .menuBar.items.menu.gain.opac
    .menuBar.items.menu.gain.opac add radiobutton -label "Correct for opacities" -variable opacityCorrect \
	    -value 1 -command {
	set statusMessage $text_replot
	if {[info exists gainChoice]} {
	    tcalkFrom $gainChoice 
	    if {$autoreplot==1} {
		replot
	    }
	}
	correctForOpacities
    }
    .menuBar.items.menu.gain.opac add radiobutton -label "No correction" -variable opacityCorrect \
	    -value 0 -command {
	set statusMessage $text_replot
	if {[info exists gainChoice]} {
	    tcalkFrom $gainChoice
	    if {$autoreplot==1} {
		replot
	    }
	}
	correctForOpacities
    }
    if {$SDmenus_is_set==0} {
	getFrequencies
	getSources
	getTimes
	getDetectors
	createSelectionMenu
	setSDmenus
	foreach rxg $LOFilelist {
	    if {[string range $rxg [expr [string length $rxg]-3] end]=="rxg"} {
		exec cp $rxg $rxg.work.$pid
	    }
	}
	for {set i 1} {$i<$number_of_datalines} {incr i} {
	    set dataMatrix($i,inUse) 1
	    set dataMatrix($i,Clicked) 1
	    set dataMatrix($i,gainBackup) $dataMatrix($i,Gain)
	    set timestr $dataMatrix($i,Time)
	    time2sec $timestr
	    set dataMatrix($i,Realtime) $timeinseconds
	}
    }
    close $fileID
    set statusMessage $text_ready
    update
}

# ---------------------------------------------------------------------------------------
# This procedure distinguishes between three cases of where TCal(K) should be read from.
# 1 = Read it from the .rxg files
# 2 = Let the user select a TCal(K)
# 3 = Let the user set the gain for some range of elevation and calculate it from TCal(Jy)
# ----------------------------------------------------------------------------------------

proc tcalkFrom choice {
    global number_of_datalines dataMatrix 
    switch $choice {
	1 {
	    for {set i 1} {$i<$number_of_datalines} {incr i} {
		set dataMatrix($i,Gain) $dataMatrix($i,gainBackup)
	    }
	}
	2 {
	    toplevel .tcalkChoice
	    wm title .tcalkChoice "Select TCal(K)"
	    label .tcalkChoice.header -text "Please select TCal(K)"
	    entry .tcalkChoice.entry -width 3 -textvariable tcalk
	    button .tcalkChoice.ok -text "OK" -command {
		set jy "TCal(Jy)"
		destroy .tcalkChoice
		for {set i 1} {$i<$number_of_datalines} {incr i} {
		    set dataMatrix($i,Gain) [expr $tcalk/$dataMatrix($i,$jy)]
		}
	    }
	    pack .tcalkChoice.header .tcalkChoice.entry .tcalkChoice.ok -in .tcalkChoice -side top -fill x
	}
	3 {
	    toplevel .tcalkChoice
	    wm title .tcalkChoice "Select Gain and Elevation Range"
	    frame .tcalkChoice.frame1
	    frame .tcalkChoice.frame2
	    frame .tcalkChoice.frame3
	    frame .tcalkChoice.frame4
	    label .tcalkChoice.gainL -text "Select Gain"
	    label .tcalkChoice.elevL1 -text "Elevation min:"
	    label .tcalkChoice.elevL2 -text "Elevation max:"
	    entry .tcalkChoice.entryG -width 6 -textvariable gain
	    entry .tcalkChoice.entryE1 -width 6 -textvariable elevmin
	    entry .tcalkChoice.entryE2 -width 6 -textvariable elevmax
	    button .tcalkChoice.ok -text "OK" -command {
		set jy "TCal(Jy)"
		if {[info exists gain]==1 && [info exists elevmin]==1 && [info exists elevmax]==1} {
		    destroy .tcalkChoice
		    set totgain 0
		    set count 0
		    for {set i 1} {$i<$number_of_datalines} {incr i} {
		        if {$dataMatrix($i,Elevation)>$elevmin && $dataMatrix($i,Elevation)<$elevmax && \
		                $dataMatrix($i,inUse)==1} {
		            set totgain [expr $totgain+$dataMatrix($i,Gain)]
		            incr count
		        }
		    }
		    set avggain [expr double($totgain)/$count]
		    for {set i 1} {$i<$number_of_datalines} {incr i} {
		        set dataMatrix($i,Gain) [expr $dataMatrix($i,Gain)*$gain/$avggain]
		    }
		} else {
		    destroy .tcalkChoice.mess
		    if {[info exists gain]==0} {
		        label .tcalkChoice.mess -text "Please enter gain." -foreground red
		        pack  .tcalkChoice.mess -in .tcalkChoice -side top -fill x
		    } else {
		        label .tcalkChoice.mess -text "Please enter elevation limits." -foreground red
		        pack  .tcalkChoice.mess -in .tcalkChoice -side top -fill x
		    }
		}
	    }
	    button .tcalkChoice.cancel -text "Cancel" -command {destroy .tcalkChoice}
	    pack .tcalkChoice.gainL .tcalkChoice.entryG -in .tcalkChoice.frame1 -side left -fill x -padx 2m
	    pack .tcalkChoice.elevL1 .tcalkChoice.entryE1 -in .tcalkChoice.frame2 -side left -fill x -padx 2m
	    pack .tcalkChoice.elevL2 .tcalkChoice.entryE2 -in .tcalkChoice.frame3 -side left -fill x -padx 2m
	    pack .tcalkChoice.ok .tcalkChoice.cancel -in .tcalkChoice.frame4 -side left -fill x -padx 2m
	    pack .tcalkChoice.frame1 -in .tcalkChoice -side top -fill y
	    pack .tcalkChoice.frame2 .tcalkChoice.frame3 -in .tcalkChoice -side top -fill y -pady 4m
	    pack .tcalkChoice.frame4 -in .tcalkChoice -side top -fill y
	}
    }
}

# -----------------------------------------
# This procedure corrects for the opacities 
# -----------------------------------------

proc correctForOpacities {} {
    global dataMatrix number_of_datalines opacityCorrect gainChoice maxvalue opacityFlag statusMessage
    set maxvalue 0
    for {set i 1} {$i<$number_of_datalines} {incr i} {
	if {$dataMatrix($i,Trec)>$maxvalue} {
	    set maxvalue $dataMatrix($i,Trec)
	    break
	}
    }
    if {$maxvalue>0} {
	if {$opacityCorrect==1} {
	    toplevel .tatmChoice
	    wm title .tatmChoice "Select Tatm"
	    label .tatmChoice.header -text "Please select Tatm"
	    entry .tatmChoice.entry -width 3 -textvariable tatm
	    button .tatmChoice.ok -text "OK" -command {
		set opacityFlag 1
		for {set i 1} {$i < $number_of_datalines} {incr i} {
		    set tsys $dataMatrix($i,Tsys)
		    set tspill $dataMatrix($i,Tspill)
		    set trec $dataMatrix($i,Trec)
		    set dataMatrix($i,Tau) [expr -log(1-($tsys-$trec-$tspill)/$tatm)]
		    if {[catch {set dataMatrix($i,Gain) [expr exp($dataMatrix($i,Tau))*$dataMatrix($i,Gain)]}]==0} {
		        set dataMatrix($i,Gain) [format %.5f [expr exp($dataMatrix($i,Tau))*$dataMatrix($i,Gain)]]
		    }
		}
		.c itemconfigure opacityHeader -text "Opacity corrected data"
		destroy .tatmChoice
		replot
	    }
	pack .tatmChoice.header .tatmChoice.entry .tatmChoice.ok -in .tatmChoice -side top -fill x
	} else {
	    tcalkFrom $gainChoice
	    set opacityFlag 0
	    replot
	    .c itemconfigure opacityHeader -text ""
	}
    } else {
	set opacityCorrect 0
	set statusMessage "No Trec in .rxg working file -> Unable to correct for opacities"
    }
}

# -------------------------------------------------------------------------------------------
# The following two procedures finds the minimum and the maximum values of a certain datatype
# stored in the dataMatrix.
# -------------------------------------------------------------------------------------------

proc min {datatype args} {
    global dataMatrix number_of_datalines minvalue xitem globaltimemin BADVALUE
    global sourcelist timelist timeAndSourceMatrix detectorlist rightfreqlist leftfreqlist
    global timeAndSourceMatrix detectorArray rightfreqArray leftfreqArray autoStyle
    set minvalue 2147483647 ;#Largest integer possible
    if {$datatype=="Airmass"} {
	set minvalue 0
    } else {
	if {$autoStyle==0} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if $dataMatrix($i,inUse)==1 {
		    if {$dataMatrix($i,$datatype) < $minvalue && $dataMatrix($i,$datatype) > [expr 0.01*$BADVALUE]} {
		        set minvalue $dataMatrix($i,$datatype)
		        if {$datatype=="Realtime"} {
		            set globaltimemin $dataMatrix($i,Time)
		        }
		    }
		}
	    }
	} else {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="l"} {
		    if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source))==1 && \
		            $leftfreqArray($dataMatrix($i,Frequency))==1} {
		        if {$dataMatrix($i,$datatype) < $minvalue && $dataMatrix($i,$datatype) > [expr 0.01*$BADVALUE]} {
		            set minvalue $dataMatrix($i,$datatype)
		            if {$datatype=="Realtime"} {
		                set globaltimemin $dataMatrix($i,Time)
		            }
		        }
		    }
		}
		if {$dataMatrix($i,Polarization)=="r"} {
		    if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source))==1 && \
		            $rightfreqArray($dataMatrix($i,Frequency))==1} {
		        if {$dataMatrix($i,$datatype) < $minvalue && $dataMatrix($i,$datatype) > [expr 0.01*$BADVALUE]} {
		            set minvalue $dataMatrix($i,$datatype)
		            if {$datatype=="Realtime"} {
		                set globaltimemin $dataMatrix($i,Time)
		            }
		        }
		    }
		}
	    }
	}  
    }
}

proc max {datatype args} {
    global dataMatrix number_of_datalines maxvalue xitem globaltimemax autoStyle
    global sourcelist timelist timeAndSourceMatrix detectorlist rightfreqlist leftfreqlist
    global timeAndSourceMatrix detectorArray rightfreqArray leftfreqArray
    set maxvalue -2147483648 ;#Smallest integer possible
    if {$autoStyle==0} {
	for {set i 1} {$i < $number_of_datalines} {incr i} {
	    if $dataMatrix($i,inUse)==1 {
		if {$dataMatrix($i,$datatype) > $maxvalue} {
		    set maxvalue $dataMatrix($i,$datatype)
		    if {$datatype=="Realtime"} {
		        set globaltimemax $dataMatrix($i,Time)
		    }
		}
	    }
	}
    } else {
	for {set i 1} {$i < $number_of_datalines} {incr i} {
	    if {$dataMatrix($i,Polarization)=="l"} {
		if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source))==1 && \
		        $leftfreqArray($dataMatrix($i,Frequency))==1} {
		    if {$dataMatrix($i,$datatype) > $maxvalue} {
		        set maxvalue $dataMatrix($i,$datatype)
		        if {$datatype=="Realtime"} {
		            set globaltimemax $dataMatrix($i,Time)
		        }
		    }   
		}
	    }
	    if {$dataMatrix($i,Polarization)=="r"} {
		if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source))==1 && \
		        $rightfreqArray($dataMatrix($i,Frequency))==1} {
		    if {$dataMatrix($i,$datatype) > $maxvalue} {
		        set maxvalue $dataMatrix($i,$datatype)
		        if {$datatype=="Realtime"} {
		            set globaltimemax $dataMatrix($i,Time)
		        }
		    } 
		}
	    }
	}
    }
}

# -------------------------------------------------------------------------------------------------
# This procedure converts a time which is easy to read "yyyy.ddd.hh:mm:ss.hh" to a format which
# is easy for the computer to understand, in this case the number of seconds since the year 1970.
# It also makes sure that tcl/tk doesn't interpret the numbers with leading zeros as octal numbers.
# -------------------------------------------------------------------------------------------------

proc time2sec {readabletime} {
    global timeinseconds
    set timestr $readabletime
    set year [string range $timestr 0 3]
    if {[string range $timestr 5 5]==0} {
	if {[string range $timestr 6 6]==0} {
	    set day [string range $timestr 7 7]
	} else {
	    set day [string range $timestr 6 7]
	}
    } else {
	set day [string range $timestr 5 7]
    }
    if {[string range $timestr 9 9]==0} {
	set hour [string range $timestr 10 10]
    } else {
	set hour [string range $timestr 9 10]
    }
    if {[string range $timestr 12 12]==0} {
	set min [string range $timestr 13 13]
    } else {
	set min [string range $timestr 12 13]
    }
    if {[string range $timestr 15 15]==0} {
	set sec [string range $timestr 16 16]
    } else {
	set sec [string range $timestr 15 16]
    }
    if {[string range $timestr 18 18]==0} {
	set sec100 [string range $timestr 19 19]
    } else {
	set sec100 [string range $timestr 18 19]
    }
    if {$year<2100} {
	set numberofleap [expr ($year-1972)/4]
    } else {
	set numberofleap [expr ($year-1972)/4-1] ;#Will work until the year 2200, after 2200 just put -2 instead of -1
    }
    incr year -1970                        ;#Years from 1970, the time will be too big an integer otherwise
    set timeinseconds [expr 31536000*$year+86400*($day+$numberofleap)+3600*$hour+60*$min+$sec+$sec100/100.0]
}

# ------------------------------------------------------------------------------------------------
# This procedure converts the computer used time format (seconds since 1970) to a readable format.
# Since the Tcl/Tk can convert UNIX time to readable time, it uses Tcl/Tk:s own features for this.
# ------------------------------------------------------------------------------------------------

proc sec2time {seconds} {
    set sec100 [expr $seconds-int($seconds)]
    set sec100 [string range $sec100 2 3]
    set therest [expr int($seconds)]
    set year [clock format $therest -format %Y]
    set day [clock format $therest -format %j]
    set time [clock format $therest -format %H:%M:%S]
    set readtime "$year.$day.$time.$sec100"
}

# ==========================================================================
#
#                             DRAWING SECTION
#
# ==========================================================================

# -----------------------------------------------------------------------------------
# This is the procedure that replots the screen. It plots only the sources, times and 
# frequencies that are selected on the "Edit" menu. It also checks that the user has
# selected more than one frequency when plotting against frequency.
# -----------------------------------------------------------------------------------

proc replot {} {
    global sourcelist xitem items dataMatrix number_of_datalines scaling leftfreqlist rightfreqlist 
    global leftfreqArray rightfreqArray currentPol timeAndSourceMatrix statusMessage gc fgc tcr ftck tck LOType
    global number_of_LO number_of_pol LONamelist LOFirstlist LOSecondlist LOFilelist currentRXG hasScaled pid
    global fittedtrecmark trecmark SDmenus_is_set source frequ pointsHighlighted
    clearScreen

    if {$items!="Gain"} {
	.c itemconfigure opacityHeader -text ""
    }
    for {set i 1} {$i < $number_of_datalines} {incr i} {
	if {($dataMatrix($i,Polarization)=="l" && $leftfreqArray($dataMatrix($i,Frequency))==1) || \
		($dataMatrix($i,Polarization)=="r" && $rightfreqArray($dataMatrix($i,Frequency))==1) && \
		$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1 && \
		$dataMatrix($i,Clicked)==1} {
	    set dataMatrix($i,inUse) 1
	} else {
	    set dataMatrix($i,inUse) 0
	}
    }
    if {$SDmenus_is_set!=1} { 
	setSDmenus
    } else {
	set source all
	set frequ all
	set pointsHighlighted 0
    }
    checkLO
    checkPol
    if {$xitem=="" || $items==""} {
	set statusMessage "Please select what you want to plot"
    } else {
	if {$number_of_LO==1 && $number_of_pol==1} {
	    foreach freq $leftfreqlist {
		if {$leftfreqArray($freq)==1} {
		    for {set i 1} {$i < $number_of_datalines} {incr i} {
		        if {$dataMatrix($i,Polarization)=="l" && $dataMatrix($i,Frequency)==$freq} {
		            set LO $dataMatrix($i,LO)
		            set currentPol "lcp"
		            break
		        }
		    }
		    break
		}
	    }
	    foreach freq $rightfreqlist {
		if {$rightfreqArray($freq)==1} {
		    for {set i 1} {$i < $number_of_datalines} {incr i} {
		        if {$dataMatrix($i,Polarization)=="r" && $dataMatrix($i,Frequency)==$freq} {
		            set LO $dataMatrix($i,LO)
		            set currentPol "rcp"
		            break
		        }
		    }
		    break
		}
	    }
	    if {$LOType=="fixed"} {
		if {[lsearch $LOFirstlist $LO]!=-1} {
		    set rxg [lindex $LOFilelist [lsearch $LOFirstlist $LO]]
		    if {[string range $rxg [expr [string length $rxg]-3] end]=="rxg"} {
		        set currentRXG $rxg.work.$pid
		    } else {
		        set currentRXG $rxg
		    }
		} elseif {[lsearch $LOSecondlist $LO]!=-1} {
		    set rxg [lindex $LOFilelist [lsearch $LOSecondlist $LO]]
		    if {[string range $rxg [expr [string length $rxg]-3] end]=="rxg"} {
		        set currentRXG $rxg.work.$pid
		    } else {
		        set currentRXG $rxg
		    }
		}
	    } elseif {$LOType=="range"} {
		set j -1
		foreach lo $LOFirstlist {
		    incr j
		    for {set i 1} {$i < $number_of_datalines} {incr i} {
		        #MC:AO
		        #18/08/2008 : workaround to avoid the selection of the second rxg file in case
		        # more than one rxg is involved
		        if {$dataMatrix($i,inUse) == 1 } {
		            if {$dataMatrix($i,LO)>=$lo && $dataMatrix($i,LO)<=[lindex $LOSecondlist $j] } {
		                set rxg [lindex $LOFilelist [lsearch $LOFirstlist $lo]]
		                if {[string range $rxg [expr [string length $rxg]-3] end]=="rxg"} {
		                    set currentRXG $rxg.work.$pid
		                } else {
		                    set currentRXG $rxg
		                }
		                break
		            }
		        }
		        #if {$dataMatrix($i,Polarization) == "l"} {
		        #    if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1 && \
		        #            $leftfreqArray($dataMatrix($i,Frequency)) == 1 && $dataMatrix($i,inUse)==1 && } {
		        #        set rxg [lindex $LOFilelist [lsearch $LOFirstlist $dataMatrix($i,LO)]]
		        #        if {[string range $rxg [expr [string length $rxg]-3] end]=="rxg"} {
		        #            set currentRXG $rxg.work.$pid
		        #        } else {
		        #            set currentRXG $rxg
		        #        }
		        #        break
		        #    }
		        #}
		        #if {$dataMatrix($i,Polarization) == "r"} {
		        #    if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1 && \
		        #            $rightfreqArray($dataMatrix($i,Frequency)) == 1 && $dataMatrix($i,inUse)==1} {
		        #       set rxg [lindex $LOFilelist [lsearch $LOFirstlist $dataMatrix($i,LO)]]
		        #       if {[string range $rxg [expr [string length $rxg]-3] end]=="rxg"} {
		        #           set currentRXG $rxg.work.$pid
		        #       } else {
		        #           set currentRXG $rxg
		        #       }
		        #       break
		        #   }
		        #}
		        #end
		    }
		}
	    }
	}
	set tempList {}
	foreach freq $leftfreqlist {
	    if {$leftfreqArray($freq) == 1} {
		lappend tempList $freq
	    }
	}
	foreach freq $rightfreqlist {
	    if {$rightfreqArray($freq) == 1} {
		if {[lsearch $tempList $freq]==-1} {
		    lappend tempList $freq
		}
	    }
	}
	if {$xitem!="Frequency" || [llength $tempList]>1} {
	    createToolsMenu $xitem
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization) == "l"} {
		    if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 0 || \
		            $leftfreqArray($dataMatrix($i,Frequency)) == 0 || $dataMatrix($i,inUse)==0 || \
		            $dataMatrix($i,Clicked)==0} {
		        set dataMatrix($i,inUse) 0
		    } else {
		        set dataMatrix($i,inUse) 1
		    }
		}
		if {$dataMatrix($i,Polarization) == "r"} {
		    if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 0 || \
		            $rightfreqArray($dataMatrix($i,Frequency)) == 0 || $dataMatrix($i,inUse)==0 || \
		            $dataMatrix($i,Clicked)==0} {
		        set dataMatrix($i,inUse) 0
		    } else {
		        set dataMatrix($i,inUse) 1
		    }
		}
	    }
	    drawNodes
	} else {
	    set statusMessage "Not enough frequencies selected. Please select more frequencies."
	}
    }
    createPointLegend
}

# ---------------------------------------------------------------------------------------------------------
# This procedure handles what is to be drawn on the screen. If a point is to be shown, it sends the number
# of that point and its pixel coordinates to the procedure plotnode. It also updates the labels of the axes
# and the drawing of source letters.
# ---------------------------------------------------------------------------------------------------------

proc drawNodes {} {
    global dataMatrix xitem items globalxmin globalxmax globalymin globalymax pixelx pixely
    global number_of_datalines sourcelist detectorlist SDmenus_is_set statusMessage
    global decimals globaltimemin globaltimemax letteroffset detectorArray text_ready number_of_pol currentPol
    global leftfreqlist rightfreqlist leftfreqArray rightfreqArray legendNo timeAndSourceMatrix text_zero
    set statusMessage "Processing..."
    update
    .c delete points
    .c delete sourcetext
    scale
    if {$globalxmin!=$globalxmax && $globalymin!=$globalymax} {
	for {set i 1} {$i<$number_of_datalines} {incr i} {
	    if {$xitem=="Time"} {
		set xval $dataMatrix($i,Realtime)
	    } else {            
		set xval $dataMatrix($i,$xitem)
	    }
	    set yval $dataMatrix($i,$items)
	    if {$dataMatrix($i,Polarization)=="l"} {
		if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1 && \
		        $leftfreqArray($dataMatrix($i,Frequency)) == 1} {
		    toPixels $xval $yval
		    plotnode $i $xval $yval
		    createSourceLetter $i $xval $yval
		}
	    }
	    if {$dataMatrix($i,Polarization)=="r"} {
		if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1 && \
		        $rightfreqArray($dataMatrix($i,Frequency)) == 1} {
		    toPixels $xval $yval
		    plotnode $i $xval $yval
		    createSourceLetter $i $xval $yval
		}
	    }
	}
    } else {
	set statusMessage $text_zero
    }
    .c itemconfigure title -text "Plotting $items vs. $xitem"
    .c itemconfigure xaxislabel -text "$xitem"
    .c itemconfigure yaxislabel -text "$items"
    if {$xitem == "Time"} {
	.c itemconfigure x0 -text [sec2time $globalxmin]
	.c itemconfigure x2 -text [sec2time $globalxmax]
	.c itemconfigure x1 -text ""
    } else {
	.c itemconfigure x0 -text "[format %.${decimals}f $globalxmin]"
	.c itemconfigure x1 -text "[format %.${decimals}f [expr ($globalxmin+$globalxmax)/2]]"
	.c itemconfigure x2 -text "[format %.${decimals}f $globalxmax]"
    }
    .c itemconfigure y0 -text "[format %.${decimals}f $globalymin]"
    .c itemconfigure y1 -text "[format %.${decimals}f [expr ($globalymin+$globalymax)/2]]"
    .c itemconfigure y2 -text "[format %.${decimals}f $globalymax]"
    if {[info exists number_of_pol]} {
	if {$number_of_pol>1} {
	    .c itemconfigure poltext -text "Both Polarizations"
	} elseif {[info exists currentPol]} {
	    if {$currentPol=="lcp"} {
		.c itemconfigure poltext -text "Left Polarization"
	    } elseif {$currentPol=="rcp"} {
		.c itemconfigure poltext -text "Right Polarization"
	    }
	}
    }
    if {$legendNo==1} {
	createSourceLegend
    }
    if {$letteroffset==0} {
	.c delete points
    }
    if {$globalxmin!=$globalxmax && $globalymin!=$globalymax} {
	set statusMessage $text_ready
    }
}

# ---------------------------------------------------------------------------------------------------
# This procedure recieves the point number from drawNodes, and the position of the point and displays 
# this on the screen. It also checks whether the point is "out of bounds" in which case it displays 
# the point on the appropriate axis.
# ---------------------------------------------------------------------------------------------------

proc plotnode {i xval yval} {
    global dataMatrix xitem items pixelx pixely pointsize globalxmin globalxmax globalymin globalymax BADVALUE
    global pointoffplot xoffset yoffset size
    if {$xval >= $globalxmin && $xval <= $globalxmax && ($yval >= $globalymin) && ($yval <= $globalymax)} {
	.c create oval [expr $pixelx-$pointsize] [expr $pixely-$pointsize] [expr $pixelx+$pointsize] \
		[expr $pixely+$pointsize] -fill white -tags point$i
	.c addtag points withtag point$i
	if {$dataMatrix($i,inUse)==0 || $dataMatrix($i,Clicked)==0} {
	    .c itemconfigure point$i -fill red
	}
    } elseif {$xval<$globalxmin} {
	if {$yval>$globalymax} {
	    .c create oval [expr $xoffset-$pointsize-$pointoffplot] [expr $yoffset-$pointsize-$pointoffplot] \
		    [expr $xoffset+$pointsize-$pointoffplot] [expr $yoffset+$pointsize-$pointoffplot] \
		    -fill white -tags point$i
	    .c addtag points withtag point$i 
	} elseif {$yval<$globalymin} {
	    .c create oval [expr $xoffset-$pointsize-$pointoffplot] \
		    [expr $size*180+$yoffset-$pointsize+$pointoffplot] [expr $xoffset+$pointsize-$pointoffplot] \
		    [expr $size*180+$yoffset+$pointsize+$pointoffplot] -fill white -tags point$i
	    .c addtag points withtag point$i 
	} else {
	    .c create oval [expr $xoffset-$pointsize-$pointoffplot] [expr $pixely-$pointsize] \
		    [expr $xoffset+$pointsize-$pointoffplot] [expr $pixely+$pointsize] -fill white -tags point$i
	    .c addtag points withtag point$i 
	}
	if {$dataMatrix($i,inUse)==0 || $dataMatrix($i,Clicked)==0 || $xval<=[expr 0.1*$BADVALUE] \
		|| $yval<=[expr 0.1*$BADVALUE]} {
	    .c itemconfigure point$i -fill red
	} else {
	    .c itemconfigure point$i -fill cyan
	}
    } elseif {$xval>$globalxmax} {
	if {$yval>$globalymax} {
	    .c create oval [expr $size*180+$xoffset-$pointsize+$pointoffplot] \
		    [expr $yoffset-$pointsize-$pointoffplot] [expr $size*180+$xoffset+$pointsize+$pointoffplot] \
		    [expr $yoffset+$pointsize-$pointoffplot] -fill white -tags point$i
	    .c addtag points withtag point$i 
	} elseif {$yval<$globalymin} {
	    .c create oval [expr $size*180+$xoffset-$pointsize+$pointoffplot] \
		    [expr $size*180+$yoffset-$pointsize+$pointoffplot] \
		    [expr $size*180+$xoffset+$pointsize+$pointoffplot] \
		    [expr $size*180+$yoffset+$pointsize+$pointoffplot] -fill white -tags point$i
	    .c addtag points withtag point$i 
	} else {
	    .c create oval [expr $size*180+$xoffset-$pointsize+$pointoffplot] [expr $pixely-$pointsize] \
		    [expr $size*180+$xoffset+$pointsize+$pointoffplot] [expr $pixely+$pointsize] \
		    -fill white -tags point$i
	    .c addtag points withtag point$i 
	}
	if {$dataMatrix($i,inUse)==0 || $dataMatrix($i,Clicked)==0 || $xval<=[expr 0.1*$BADVALUE] \
		|| $yval<=[expr 0.1*$BADVALUE]} {
	    .c itemconfigure point$i -fill red
	} else {
	    .c itemconfigure point$i -fill cyan
	}
    } elseif {$xval>$globalxmin && $xval<$globalxmax} {
	if {$yval>$globalymax} {
	    .c create oval [expr $pixelx-$pointsize] [expr $yoffset-$pointsize-$pointoffplot] \
		    [expr $pixelx+$pointsize] [expr $yoffset+$pointsize-$pointoffplot] \
		    -fill white -tags point$i
	    .c addtag points withtag point$i 
	} elseif {$yval<$globalymin} {
	    .c create oval [expr $pixelx-$pointsize] [expr $size*180+$yoffset-$pointsize+$pointoffplot] \
		    [expr $pixelx+$pointsize] [expr $size*180+$yoffset+$pointsize+$pointoffplot] \
		    -fill white -tags point$i
	    .c addtag points withtag point$i 
	}
	if {$dataMatrix($i,inUse)==0 || $dataMatrix($i,Clicked)==0 || $xval<=[expr 0.1*$BADVALUE] \
		|| $yval<=[expr 0.1*$BADVALUE]} {
	    .c itemconfigure point$i -fill red
	} else {
	    .c itemconfigure point$i -fill cyan
	}
    }
}


# -----------------------------------------------------------------------------------------
# The following two procedures converts coordinates to pixels and vice versa. The first one
# gets the "real" values of x and y, converts them into "pixel" values of x and y, stored
# in the variables pixelx and pixely. The second one gets the "pixel" values px and py, and
# converts them inte "real" values stored in the variables coordx and coordy.
# -----------------------------------------------------------------------------------------

proc toPixels {x y} {
    global xoffset yoffset size globalxmin globalxmax globalymin globalymax pixelx pixely
    set x0 double($xoffset)              ;#left x-value
    set x1 [expr $size*180+$xoffset]     ;#right x-value
    set y0 double($yoffset)              ;#upper y-value
    set y1 [expr $size*180+$yoffset]     ;#lower y-value
    set fx [expr ($x-$globalxmin)/(double($globalxmax)-double($globalxmin))]
    set fy [expr ($y-$globalymin)/($globalymax-$globalymin)]
    set xs [expr $x1-$x0]
    set ys [expr $y1-$y0]
    set pixelx [expr $fx*$xs+$x0]
    set pixely [expr (1-$fy)*$ys+$y0]
}

proc toCoordinates {px py} {
    global globalxmin globalxmax globalymin globalymax coordx coordy xoffset yoffset size xitem
    global globaltimemin globaltimemax timeinseconds
    set x0 double($xoffset)              ;#left x-value, $fx has to be a double
    set x1 [expr $size*180+$xoffset]     ;#right x-value
    set y0 double($yoffset)              ;#upper y-value, $fy has to be a double
    set y1 [expr $size*180+$yoffset]     ;#lower y-value
    set fx [expr ($px-$x0)/($x1-$x0)]
    set fy [expr ($py-$y0)/($y1-$y0)]
    set xs [expr $globalxmax-$globalxmin]
    set ys [expr $globalymax-$globalymin]
    set coordx [expr $fx*$xs+$globalxmin]
    set coordy [expr (1-$fy)*$ys+$globalymin]
}

# ----------------------------------------------------
# This procedure clears curves from the current screen
# ----------------------------------------------------

proc clearScreen {} {
    global gc fgc tcr ftck tck fittedtrecmark trecmark
    set gc 0
    set fgc 0
    set tck 0
    set ftck 0
    set tcr 0
    set trecmark 0            
    set fittedtrecmark 0
    .c delete connectCurve
    .c delete gaincurve
    .c delete fittedgaincurve
    .c delete tcalcurve
    .c delete fittedtcalcurve
    .c delete tcrcurve
    .c delete trecmarker
    .c delete fittedtrecmarker
    .c delete fittedtrecmarkaverage
    .c delete treccurve
}

# --------------------------------------------------------------------------------------------------------
# This procedure draws a polynomial, most likely a gain curve. It recieves a DPFU, a list of coefficients,
# a name of the polynomial (tag), what type of curve it is (ELEV or ALTAZ) and it also takes optional
# arguments, so far only one and that is if the curve should be dashed or not.
# --------------------------------------------------------------------------------------------------------

proc drawPoly {DPFU coefflist tag type args} {
    global globalxmin globalxmax globalymin globalymax pixelx pixely statusMessage pointoffplot 
    global xitem items minvalue maxvalue hasScaled gc fgc thickline opacityFlag opacityCurveCorrect
    if {[lindex $coefflist end]=="opacity_corrected"} {
	set coefflist [lrange $coefflist 0 [expr [llength $coefflist]-2]]
	if {$opacityFlag==1} {
	    .c itemconfigure opacityHeader -text "Opacity corrected data and gain curve"
	} else {
	    .c itemconfigure opacityHeader -text "Opacity corrected gain curve"
	}        
    }
    if {$tag=="fittedgaincurve"} {
	set fgc 1
    } elseif {$tag=="gaincurve"} {
	set gc 1
    }
    if {![info exists oldtype]} {
	set oldtype $type
    }
    set args [split [string trim $args "\{\}"]]
    set dash 0
    if {[lindex $args 0]=="dash"} {
	set dash 5
    }
    if {[llength $args]>1} {
	set color [lindex $args 1]
    } else {
	set color black
    }
    if {$color!="black"} {
	set width $thickline
    } else {
	set width 2
    }
    set reScaled 0
    if {$hasScaled==1} {
	set hasScaled 0
    }
    set step 200
    #This if statement checks if the type of gain curve (ELEV or ALTAZ) has changed since the last drawing
    #If it has, it just switches to the other one. Since the procedure divides the x-axis into $step
    #(default=200) pieces, only the first and last value of the axis are needed.
    if {$type!=$oldtype} {
	set globalxmin [expr 90-$globalxmin]
	set globalxmax [expr 90-$globalxmax]
    }
    toPixels $globalxmin $globalymin
    set pixelxmin $pixelx
    set pixelymax $pixely   ;# reverse coordinate system
    toPixels $globalxmax $globalymax
    set pixelxmax $pixelx
    set pixelymin $pixely   ;# reverse coordinate system
    set range [expr $globalxmax-$globalxmin]
    set xold $globalxmin
    set yold 0
    set ylist {}
    for {set j 0} {$j<[llength $coefflist]} {incr j} {
	set yold [expr $yold+[lindex $coefflist $j]*pow($xold,$j)]
    }
    lappend ylist $yold
    for {set i 1} {$i<=$step} {incr i} {
	set xnew [expr double($globalxmin)+double($range)/double($step)*$i]
	set ynew 0
	for {set j 0} {$j<[llength $coefflist]} {incr j} {
	    set ynew [expr $ynew+[lindex $coefflist $j]*pow($xnew,$j)]
	}
	lappend ylist $ynew
	toPixels $xold [expr $DPFU*$yold]
	set pixelxold $pixelx
	set pixelyold $pixely
	toPixels $xnew [expr $DPFU*$ynew]
	set pixelxnew $pixelx
	set pixelynew $pixely
	if {($pixelxold>=$pixelxmin && $pixelxold<=$pixelxmax) && ($pixelxnew>=$pixelxmin && $pixelxnew<=$pixelxmax) && \
		($pixelyold>=[expr $pixelymin-$pointoffplot] && $pixelyold<=[expr $pixelymax+$pointoffplot]) && \
		($pixelynew>=[expr $pixelymin-$pointoffplot] && $pixelynew<=[expr $pixelymax+$pointoffplot])} {
	    .c create line $pixelxold $pixelyold $pixelxnew $pixelynew -tags $tag -fill $color -width $width
	}
	if {[lindex $args 0]=="dash" && [expr $i%$dash]==0} {
	    incr i $dash 
	    set xold [expr double($globalxmin)+double($range)/double($step)*$i]
	    set yold 0
	    for {set j 0} {$j<[llength $coefflist]} {incr j} {
		set yold [expr $yold+[lindex $coefflist $j]*pow($xold,$j)]
	    }
	} else {
	    set xold $xnew
	    set yold $ynew
	}
    }
    set ymax [lindex [lsort -real $ylist] end]
    set ymin [lindex [lsort -real $ylist] 0]
    if {[expr $DPFU*$ymax]>$globalymax || [expr $DPFU*$ymin]<$globalymin} {
	if {[expr $DPFU*$ymin]<$globalymin} {
	    set globalymin [expr $DPFU*$ymin]
	}
	if {[expr $DPFU*$ymax]>$globalymax} {
	    set globalymax [expr $DPFU*$ymax]
	}
	set hasScaled 1
	.c delete $tag
	replot
	set reScaled 1
    }
    if {$reScaled==1} {
	drawPoly $DPFU $coefflist $tag $type $args
    }
    set oldtype $type
    set statusMessage "Ready."
}

proc drawTCalCurve {xstart ystart xstop ystop tag args} {
    global globalxmin globalxmax globalymin globalymax pixelx pixely statusMessage pointoffplot 
    global xitem items minvalue maxvalue hasScaled gc fgc thickline
    if {$tag=="tcalcurve"} {
	set color green3
	set width $thickline
    } else {
	set color red
	set width 2
    }
    set dash 0
    if {[lindex $args 0]=="dash"} {
	set dash 3
    }
    toPixels $globalxmin $globalymin
    set pixelxmin $pixelx
    set pixelymax $pixely   ;# reverse coordinate system
    toPixels $globalxmax $globalymax
    set pixelxmax $pixelx
    set pixelymin $pixely   ;# reverse coordinate system
    toPixels $xstart $ystart
    set pixelxstart $pixelx
    set pixelystart $pixely
    toPixels $xstop $ystop
    set pixelxstop $pixelx
    set pixelystop $pixely
    set dist [expr sqrt(pow(($pixelxstart-$pixelxstop),2)+pow(($pixelystart-$pixelystop),2))]
    set step [expr $dist/3]
    set range [expr $xstop-$xstart]
    #MC:AO added to manage the case x1=x2 => division by zero!
    if {$xstop==$xstart} {     
	    if {($pixelxstart>=$pixelxmin && $pixelxstart<=$pixelxmax) && ($pixelxstop>=$pixelxmin && $pixelxstop<= \
		$pixelxmax) && ($pixelystart>=[expr $pixelymin-$pointoffplot] && $pixelystart<=[expr $pixelymax+ \
		$pointoffplot]) && ($pixelystop>=[expr $pixelymin-$pointoffplot] && $pixelystop<=[expr $pixelymax+$pointoffplot])} {
		.c create line $pixelxstart $pixelystart $pixelxstop $pixelystop -tags $tag -fill $color -width $width \
		    -joinstyle round
	    }   
	    return
    }
    set k [expr ($ystop-$ystart)/($xstop-$xstart)]
    set m [expr $ystop-($ystop-$ystart)/($xstop-$xstart)*$xstop]
    set coefflist {$m $k}
    set xold $xstart
    set yold 0
    set ylist {}
    for {set j 0} {$j<[llength $coefflist]} {incr j} {
	set yold [expr $yold+[lindex $coefflist $j]*pow($xold,$j)]
    }
    lappend ylist $yold
    for {set i 1} {$i<=$step} {incr i} {
	set xnew [expr double($xstart)+double($range)/double($step)*$i]
	set ynew 0
	for {set j 0} {$j<[llength $coefflist]} {incr j} {
	    set ynew [expr $ynew+[lindex $coefflist $j]*pow($xnew,$j)]
	}
	lappend ylist $ynew
	toPixels $xold $yold
	set pixelxold $pixelx
	set pixelyold $pixely
	toPixels $xnew $ynew
	set pixelxnew $pixelx
	set pixelynew $pixely
	if {($pixelxold>=$pixelxmin && $pixelxold<=$pixelxmax) && ($pixelxnew>=$pixelxmin && $pixelxnew<=$pixelxmax) && \
		($pixelyold>=[expr $pixelymin-$pointoffplot] && $pixelyold<=[expr $pixelymax+$pointoffplot]) && \
		($pixelynew>=[expr $pixelymin-$pointoffplot] && $pixelynew<=[expr $pixelymax+$pointoffplot])} {
	    .c create line $pixelxold $pixelyold $pixelxnew $pixelynew -tags $tag -fill $color -width $width \
		-joinstyle round
	}
	if {[lindex $args 0]=="dash" && [expr $i%$dash]==0} {
	    incr i $dash 
	    set xold [expr double($xstart)+double($range)/double($step)*$i]
	    set yold 0
	    for {set j 0} {$j<[llength $coefflist]} {incr j} {
		set yold [expr $yold+[lindex $coefflist $j]*pow($xold,$j)]
	    }
	} else {
	    set xold $xnew
	    set yold $ynew
	}
    }
}
 
proc drawTrecCurve {trec tau tatm tag args} {
    global globalxmin globalxmax globalymin globalymax pixelx pixely statusMessage pointoffplot 
    global xitem items minvalue maxvalue hasScaled gc fgc thickline
    set step 200
    if {$tag=="tcalcurve"} {
	set color green3
	set width $thickline
    } else {
	set color black
	set width 1
    }
    set dash 0
    if {[lindex $args 0]=="dash"} {
	set dash 3
    }
    toPixels $globalxmin $globalymin
    set pixelxmin $pixelx
    set pixelymax $pixely   ;# reverse coordinate system
    toPixels $globalxmax $globalymax
    set pixelxmax $pixelx
    set pixelymin $pixely   ;# reverse coordinate system
    set range [expr $globalxmax-$globalxmin]
    set ylist {}
    set xold $globalxmin
    set yold [expr $trec+$tatm*(1-exp(-$tau*$xold))]
    lappend ylist $yold
    for {set i 1} {$i<=$step} {incr i} {
	set xnew [expr double($globalxmin)+double($range)/double($step)*$i]
	set ynew [expr $trec+$tatm*(1-exp(-$tau*$xnew))]
	lappend ylist $ynew
	toPixels $xold $yold
	set pixelxold $pixelx
	set pixelyold $pixely
	toPixels $xnew $ynew
	set pixelxnew $pixelx
	set pixelynew $pixely
	if {($pixelxold>=$pixelxmin && $pixelxold<=$pixelxmax) && ($pixelxnew>=$pixelxmin && $pixelxnew<=$pixelxmax) && \
		($pixelyold>=[expr $pixelymin-$pointoffplot] && $pixelyold<=[expr $pixelymax+$pointoffplot]) && \
		($pixelynew>=[expr $pixelymin-$pointoffplot] && $pixelynew<=[expr $pixelymax+$pointoffplot])} {
	    .c create line $pixelxold $pixelyold $pixelxnew $pixelynew -tags $tag -fill $color -width $width
	}
	if {[lindex $args 0]=="dash" && $i%$dash==0} {
	    incr i $dash 
	    set xold [expr double($globalxmin)+double($range)/double($step)*$i]
	    set yold [expr $trec+$tatm*(1-exp(-$tau*$xold))]
	} else {
	    set xold $xnew
	    set yold $ynew
	}
    }
}


# -----------------------------------------------------------------------------------------------
# This procedure displays the current values for certain items to the right of the plotting area.
# It is run when the user moves the mouse pointer over the point.
# -----------------------------------------------------------------------------------------------

proc updatePointData {} {
    global dataMatrix PointX PointY PointSource PointAzimuth PointElevation PointDetector 
    global xitem items XPointLabel YPointLabel PointTime PointFreq PointPol
    set taglist [.c gettags current]
    set node [string range [lindex $taglist 0] 5 end]
    set XPointLabel "[string range $xitem 0 8]:"
    set YPointLabel "[string range $items 0 8]:"
    set PointX $dataMatrix($node,$xitem)
    set PointY $dataMatrix($node,$items)
    set PointSource $dataMatrix($node,Source)
    set PointFreq $dataMatrix($node,Frequency)
    set PointPol $dataMatrix($node,Polarization)
    set PointAzimuth $dataMatrix($node,Azimuth)
    set PointElevation $dataMatrix($node,Elevation)
    set PointTime $dataMatrix($node,Time)
}

# ------------------------------------------------------------------------------------------
# This procedure clears the point data from the screen when the mouse leaves the data point)
# ------------------------------------------------------------------------------------------

proc clearPointData {} {
    global PointX PointY PointSource PointDetector PointElevation PointTime PointFreq PointPol PointAzimuth
    set PointX ""
    set PointY ""
    set PointSource ""
    set PointFreq ""
    set PointPol ""
    #set PointDetector ""
    set PointAzimuth ""
    set PointElevation ""
    set PointTime ""
}

# ==========================================================================
#
#                             SCALING SECTION
#
# ==========================================================================

# ---------------------------------------------------------------------------------------------------------
# The following procedures controls the scaling of the axes. scale only checks what type of scaling to use,
# and the actual scaling is done by autoScale and scaleManual.
# ---------------------------------------------------------------------------------------------------------

proc scale {} {
    global scaling hasScaled gc fgc tcr frequ source ftck tck fittedtrecmark trecmark
    if ($hasScaled==-1) {
	autoScale 
    } else {
	if ($hasScaled==0) {
	    if [string match $scaling Manual] {
		scaleManual
	    } else {
		autoScale
	    }
	}
    }
    clearScreen
    set frequ all
    set source all
}

# -------------------------------------------------------------------------------------------
# This procedure autoscales the current plot. It uses the min and max procedures to determine 
# the limits for the plot.
# -------------------------------------------------------------------------------------------

proc autoScale {} {
    global xitem items minvalue maxvalue globalxmin globalxmax globalymin globalymax hasScaled statusMessage text_zero
    if {$xitem=="Time"} {
	min Realtime
	set globalxmin $minvalue
	max Realtime
	set globalxmax $maxvalue
    } else {
	min $xitem
	set globalxmin $minvalue
	max $xitem
	set globalxmax $maxvalue
    }
    min $items 
    set globalymin $minvalue
    max $items 
    set globalymax $maxvalue
    if {$globalxmin!=$globalxmax && $globalymin!=$globalymax} {
	if ($hasScaled==1) {
	    drawNodes
	}
	set hasScaled 0
    } else {
	set statusMessage $text_zero
    }
} 

# -------------------------------------------------------------------------------------------------
# This procedure lets the user manually scale the axes, which basically only is setting the limits.
# It also uses the procedure checkScaling to see whether the user has selected proper limits.
# -------------------------------------------------------------------------------------------------

proc scaleManual {} {
    global globalxmin globalxmax globalymin globalymax oldxmin oldxmax oldymin oldymax hasScaled scalingok
    global xitem globaltimemin globaltimemax timeinseconds statusMessage scaling
    if {[info exists globalxmin]} {
	set hasScaled 1
	toplevel .scaleWindow
	wm title .scaleWindow "Manual scaling"
	set scalingList {X-min X-max Y-min Y-max}
	if {$xitem=="Time"} {
	    set limitList {globaltimemin globaltimemax globalymin globalymax}
	    time2sec $globaltimemin
	    set globalxmin $timeinseconds
	    time2sec $globaltimemax
	    set globalxmax $timeinseconds
	} else {
	    set limitList {globalxmin globalxmax globalymin globalymax}
	}
	set oldxmin $globalxmin
	set oldxmax $globalxmax
	set oldymin $globalymin
	set oldymax $globalymax
	foreach i {0 1 2 3} {
	    frame .scaleWindow.entries$i
	    label .scaleWindow.entries$i.scalelabel$i -text [lindex $scalingList $i]
	    entry .scaleWindow.entries$i.scaleentry$i -width 20 -relief sunken -textvariable [lindex $limitList $i]
	    pack .scaleWindow.entries$i.scalelabel$i .scaleWindow.entries$i.scaleentry$i \
		    -side left -in .scaleWindow.entries$i
	    pack .scaleWindow.entries$i -in .scaleWindow -side top
	}
	button .scaleWindow.ok -text OK -command {
	    if {$xitem=="Time"} {
		time2sec $globaltimemin
		set globalxmin $timeinseconds
		time2sec $globaltimemax
		set globalxmax $timeinseconds
	    }
	    checkScaling
	    if {$scalingok == 0} {
		destroy .scaleWindow
		drawNodes
	    } elseif {$scalingok == 1} {
		destroy .scaleWindow.wrongscaling
		label .scaleWindow.wrongscaling -text "Bad limits, please change" -foreground red -padx 3m -pady 3m
		pack .scaleWindow.wrongscaling -in .scaleWindow -side top -anchor s
	    }
	}
	button .scaleWindow.cancel -text Cancel -command {
	    destroy .scaleWindow;  
	    set globalxmin $oldxmin
	    set globalxmax $oldxmax
	    set globalymin $oldymin
	    set globalymax $oldymax
	}
	pack .scaleWindow.ok -in .scaleWindow -side left -fill x
	pack .scaleWindow.cancel -in .scaleWindow -side right -fill x
    } else {
	set statusMessage "No axes selected."
	set scaling Auto
    }
}

# -----------------------------------------------------------------------------
# This procedure checks whether the user has set the manual limits "correctly".
# -----------------------------------------------------------------------------

proc checkScaling {} {
    global globalxmin globalxmax globalymin globalymax scalingok
    if {$globalxmin <= $globalxmax && $globalymin <= $globalymax} {
	set scalingok 0
    } else {
	set scalingok 1
    }
}

# -------------------------------------------------------------------------------------
# This procedure makes all the sources, detectors, frequencies etc. be displayed again.
# It is particulary useful when the display, for some reason, doesn't quite respond to 
# your request.
# -------------------------------------------------------------------------------------

proc showAll {} {
    global dataMatrix number_of_datalines hasScaled scaling sourcedisplay letteroffset
    global sourcelist timelist timeAndSourceMatrix detectorlist rightfreqlist leftfreqlist
    global timeAndSourceMatrix detectorArray rightfreqArray leftfreqArray
    set sourcedisplay 2
    set letteroffset 3 
    set hasScaled 0
    set scaling Auto
    for {set i 1} {$i<=$number_of_datalines} {incr i} {
	set dataMatrix($i,inUse) 1
    }
    foreach source $sourcelist {
	foreach time $timelist {
	    set timeAndSourceMatrix($time,$source) 1
	}
    }
    foreach detector $detectorlist {
	set detectorArray($detector) 1
    }
    foreach freq $rightfreqlist {
	set rightfreqArray($freq) 1
    }
    foreach freq $leftfreqlist {
	set leftfreqArray($freq) 1
    }
    checkPol
    drawNodes
    .c itemconfigure points -fill white
}

proc showAlmostAll {} {
    global dataMatrix number_of_datalines hasScaled scaling sourcedisplay letteroffset
    global sourcelist timelist timeAndSourceMatrix detectorlist rightfreqlist leftfreqlist
    global timeAndSourceMatrix detectorArray rightfreqArray leftfreqArray
    set sourcedisplay 2
    set letteroffset 3 
    set hasScaled 0
    set scaling Auto
    .c itemconfigure points -fill white
    for {set i 1} {$i<=$number_of_datalines} {incr i} {
	if {$dataMatrix($i,Polarization)=="l"} {
	    if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source))==1 && \
		    $leftfreqArray($dataMatrix($i,Frequency))==1} {
		set dataMatrix($i,inUse) 1
		set dataMatrix($i,Clicked) 1
		.c itemconfigure point$i -fill white
	    }
	}
	if {$dataMatrix($i,Polarization)=="r"} {
	    if {$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source))==1 && \
		    $rightfreqArray($dataMatrix($i,Frequency))==1} {
		set dataMatrix($i,inUse) 1
		set dataMatrix($i,Clicked) 1
		.c itemconfigure point$i -fill white
	    }
	}
    }
    drawNodes
}


# -------------------------------------------------------------------------------------------------
# The following procedures allows the user to zoom with a box by clicking the left mouse button and
# holding it down to drag the box. 
# -------------------------------------------------------------------------------------------------

proc boxZoom {x y} {
    global xstart ystart globalxmin globalxmax globalymin globalymax hasScaled coordx coordy
    if {[info exists xstart]} {
	if {($xstart>$x-5 && $xstart<$x+5) || ($ystart>$y-5 && $ystart<$y+5)} {
	} else {
	    clearScreen
	    toCoordinates $xstart $ystart
	    set xstart $coordx
	    set ystart $coordy
	    toCoordinates $x $y
	    set x $coordx
	    set y $coordy
	    if {$x < $xstart} {
		set globalxmin $x
		set globalxmax $xstart
	    } else {
		set globalxmin $xstart
		set globalxmax $x
	    }
	    if {$y < $ystart} {
		set globalymin $y
		set globalymax $ystart
	    } else {
		set globalymin $ystart
		set globalymax $y
	    }
	    .c delete box
	    set hasScaled 1
	    drawNodes
	}
	.c delete box
    }
}

proc boxChange {x y changeTo} {
    global xstart ystart dataMatrix number_of_datalines xitem items coordx coordy leftfreqArray rightfreqArray
    global timeAndSourceMatrix pointsIncluded
    if {[info exists xstart] && [info exists items] && [info exists xitem]} {
	if {($xstart>$x-5 && $xstart<$x+5) || ($ystart>$y-5 && $ystart<$y+5)} {
	} else {
	    toCoordinates $xstart $ystart
	    set xstart $coordx
	    set ystart $coordy
	    toCoordinates $x $y
	    set x $coordx
	    set y $coordy
	    if {$xstart>$x} {
		set temp $xstart
		set xstart $x
		set x $temp
	    }
	    if {$ystart>$y} {
		set temp $ystart
		set ystart $y
		set y $temp
	    }
	    if {$xitem=="Time"} {
		set xitem Realtime
	    }
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,$xitem) >= $xstart && $dataMatrix($i,$xitem) <= $x && \
		        $dataMatrix($i,$items) >= $ystart && $dataMatrix($i,$items) <= $y && \
		        (($dataMatrix($i,Polarization)=="l" && $leftfreqArray($dataMatrix($i,Frequency))==1) || \
		             ($dataMatrix($i,Polarization)=="r" && $rightfreqArray($dataMatrix($i,Frequency))==1)) && \
		        $timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1} {
		    if {$changeTo==0} {
		        if {$dataMatrix($i,inUse)!=0 && $dataMatrix($i,Clicked)!=0} {
		            incr pointsIncluded -1
		        }
		        set dataMatrix($i,inUse) 0
		        set dataMatrix($i,Clicked) 0
		        .c itemconfigure point$i -fill red
		    } else {
		        if {$dataMatrix($i,inUse)==0 && $dataMatrix($i,Clicked)==0} {
		            incr pointsIncluded
		        }
		        set dataMatrix($i,inUse) 1
		        set dataMatrix($i,Clicked) 1
		        .c itemconfigure point$i -fill white
		    }
		}
	    }
	    if {$xitem=="Realtime"} {
		set xitem Time
	    }
	}
	.c delete box
    }
}


proc boxBegin {w x y} {
    global box xstart ystart
    set xstart $x
    set ystart $y
    set box($w,anchor) [list $x $y]
    catch {unset box($w,last)}
}

proc boxDrag {w x y} {
    global box
    catch {$w delete $box($w,last)}
    set box($w,last) [eval {$w create rect} $box($w,anchor) {$x $y -tag box}]
}

# ==========================================================================
#
#               SOURCES, DETECTORS, TIMES & FREQUENCIES SECTION
#
# ==========================================================================

# ---------------------------------------------------------------------------------------------------------
# The following two procedures displays the source letters and the source legend next to the plotting area.
# ---------------------------------------------------------------------------------------------------------

proc createSourceLetter {i xval yval} {
    global sourcelist dataMatrix number_of_datalines pointsize xitem items pixelx pixely sourcedisplay
    global globalxmin globalxmax globalymin globalymax
    global letteroffset sourceLetterList sourceColourList
    if {$sourcedisplay} {
	set sourceNo [lsearch $sourcelist $dataMatrix($i,Source)]
	if {$xval>=$globalxmin && $xval<=$globalxmax && $yval>=$globalymin && $yval<=$globalymax} {
	    .c create text [expr $pixelx+$letteroffset*$pointsize] $pixely -text [lindex $sourceLetterList $sourceNo] \
		-fill [lindex $sourceColourList $sourceNo] -tags stext$i 
	    .c addtag sourcetext withtag stext$i
	}
    }
}



proc createSourceLegend {} {
    global sourcelist sourceLetterList sourceColourList legendNo
    if {$legendNo==1} {
	destroy .sourceLegendHeader
	destroy .subframe201
	destroy .subframe202
	frame .subframe201
	frame .subframe202
	pack .subframe201 .subframe202 -side left -in .subframe20 -fill x
	label .sourceLegendHeader -text "Source Legend"
	pack .sourceLegendHeader -in .subframe200 -side top -anchor n
	set i 0
	foreach sou $sourcelist {
	    label .subframe201.sourceLegendLabel$sou -text [lindex $sourceLetterList $i] \
		    -fg [lindex $sourceColourList $i] 
	    pack .subframe201.sourceLegendLabel$sou -in .subframe201 -side top
	    label .subframe202.sourceNameLabel$sou -text [lindex $sourcelist $i] -fg black
	    pack .subframe202.sourceNameLabel$sou -in .subframe202 -side top
	    incr i
	}
    }
    set legendNo 0
}


proc createPointLegend {} {
    global dataMatrix number_of_datalines xitem items leftfreqArray rightfreqArray sourcelist timeAndSourceMatrix
    global pointsSelected pointsDeleted pointsIncluded
    set pointsDeleted 0
    set pointsSelected 0
    set pointsIncluded 0
    for {set i 1} {$i < $number_of_datalines} {incr i} {
	if {(($dataMatrix($i,Polarization)=="l" && $leftfreqArray($dataMatrix($i,Frequency))==1) || \
		 ($dataMatrix($i,Polarization)=="r" && $rightfreqArray($dataMatrix($i,Frequency))==1)) && \
		$timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1} {
	    incr pointsSelected
	    if {$dataMatrix($i,Clicked)==0} {
		incr pointsDeleted
	    }
	}
    }
    set pointsIncluded [expr $pointsSelected-$pointsDeleted]
}

# -------------------------------------------------------------------------------------------
# The following procedures creates the lists of sources, detectors, frequencies and times.
# Also the matrix that contains the times of which different sources was observed is created.
# -------------------------------------------------------------------------------------------

proc getSources {} {
    global dataMatrix number_of_datalines sourcelist BADSTRVALUE sourcetypelist
    for {set i 1} {$i < $number_of_datalines} {incr i} {
	set count [lsearch $sourcelist $dataMatrix($i,Source)]
	if {$count>=0 || $dataMatrix($i,Source) == $BADSTRVALUE} {
	} else {
	    lappend sourcelist $dataMatrix($i,Source)
	    lappend sourcetypelist $dataMatrix($i,SourceType)
	}
    }
}

proc getDetectors {} {
    global dataMatrix number_of_datalines detectorlist BADSTRVALUE
    for {set i 1} {$i < $number_of_datalines} {incr i} {
	set count [lsearch $detectorlist $dataMatrix($i,Detector)]
	if {$count>=0 || $dataMatrix($i,Detector) == $BADSTRVALUE} {
	} else {
	    lappend detectorlist $dataMatrix($i,Detector)
	}
    }
}

proc getTimes {} {
    global dataMatrix number_of_datalines timelist BADSTRVALUE sourcelist currentOutputFile timesforsources
    for {set i 1} {$i < $number_of_datalines} {incr i} {
	set count [lsearch $timelist $dataMatrix($i,Time)]
	if {$count>=0 || $dataMatrix($i,Time) == $BADSTRVALUE} {
	} else {
	    lappend timelist $dataMatrix($i,Time)
	}
    }
    foreach source $sourcelist {
	foreach time $timelist {
	    if {[catch {exec grep "$time $source" $currentOutputFile}]} {
		set timesforsources($time,$source) 0
	    } else {
		set timesforsources($time,$source) 1
	    }
	}
    }
}

proc getFrequencies {} {
    global dataMatrix number_of_datalines leftfreqlist rightfreqlist BADSTRVALUE leftfreqLOlist rightfreqLOlist
    global leftfreqLabellist rightfreqLabellist
    for {set i 1} {$i < $number_of_datalines} {incr i} {
	if {$dataMatrix($i,Polarization)=="r"} {
	    set count [lsearch $rightfreqlist $dataMatrix($i,Frequency)]
	    if {$count>=0 || $dataMatrix($i,Frequency) == $BADSTRVALUE} {
	    } else {
		lappend rightfreqlist $dataMatrix($i,Frequency)
	    }
	}
	if {$dataMatrix($i,Polarization)=="l"} {
	    set count [lsearch $leftfreqlist $dataMatrix($i,Frequency)]
	    if {$count>=0 || $dataMatrix($i,Frequency) == $BADSTRVALUE} {
	    } else {
		lappend leftfreqlist $dataMatrix($i,Frequency)
	    }
	}
    }
    set rightfreqlist [lsort -real $rightfreqlist]
    set leftfreqlist [lsort -real $leftfreqlist]
    foreach frequency $rightfreqlist {
	for {set j 1} {$j < $number_of_datalines} {incr j} {
	    if {$dataMatrix($j,Frequency) == $frequency && $dataMatrix($j,Polarization)=="r"} {
		lappend rightfreqLabellist $dataMatrix($j,Detector)
		lappend rightfreqLOlist $dataMatrix($j,LO)
		break
	    }
	}
    }
    foreach frequency $leftfreqlist {
	for {set j 1} {$j < $number_of_datalines} {incr j} {
	    if {$dataMatrix($j,Frequency) == $frequency && $dataMatrix($j,Polarization)=="l"} {
		lappend leftfreqLabellist $dataMatrix($j,Detector)
		lappend leftfreqLOlist $dataMatrix($j,LO)
		break
	    }
	}
    }
}

# ----------------------------------------------------------------------------------
# The following procedure creates the higlighting menus for sources and frequencies.
# The procedure after that does the actual higlighting.
# ----------------------------------------------------------------------------------
    
proc setSDmenus {} {
    global sourcelist detectorlist source currentPolSDmenus_is_set letteroffset sourcedisplay leftfreqlist rightfreqlist
    global frequ leftfreqLabellist rightfreqLabellist leftfreqArray rightfreqArray sourceLetterList pointsHighlighted 
    global SDmenus_is_set
    destroy .menuBar.source.menu
    destroy .menuBar.frequ.menu
    menu .menuBar.source.menu
    menu .menuBar.frequ.menu
    .menuBar.source.menu add radiobutton -label "All sources" -variable source -value all -command highlight
    .menuBar.source.menu add separator
    .menuBar.frequ.menu add radiobutton -label "All Frequencies" -variable frequ -value all -command highlight
    .menuBar.frequ.menu add separator
    set i 0
    foreach sou $sourcelist {
	.menuBar.source.menu add radiobutton -label "$sou [lindex $sourceLetterList $i]" \
		-variable source -value [lindex $sourcelist $i] -command highlight
	incr i
    }
    .menuBar.source.menu add separator
    .menuBar.source.menu add cascade -label "Select Display" -menu .menuBar.source.menu.display
    menu .menuBar.source.menu.display
    .menuBar.source.menu.display add radiobutton -label "Points" -variable sourcedisplay -value 0 \
	    -command {
	set letteroffset 3
	set statusMessage "Replotting needed..."
	update 
    }
    .menuBar.source.menu.display add radiobutton -label "Letters"  -variable sourcedisplay -value 1 \
	    -command {
	set letteroffset 0
	set statusMessage "Replotting needed..."
	update
    }
    .menuBar.source.menu.display add radiobutton -label "Points and Letters"  -variable sourcedisplay -value 2 \
	    -command {
	set letteroffset 3
	set statusMessage "Replotting needed..."
	update
    }
    #getDetectors
    set i 0
    set k 0
    foreach lf $leftfreqlist {
	incr k
	if {[expr $k%30]==0} {
	    if {$leftfreqArray($lf) == 1} {
		.menuBar.frequ.menu add radiobutton -label "$lf [lindex $leftfreqLabellist $i] l" \
		        -variable frequ -value [lindex $leftfreqlist $i]l -columnbreak 1 -command highlight
	    }
	} else {
	if {$leftfreqArray($lf) == 1} {
		.menuBar.frequ.menu add radiobutton -label "$lf [lindex $leftfreqLabellist $i] l" \
		        -variable frequ -value [lindex $leftfreqlist $i]l -columnbreak 0 -command highlight
	    }
	}
	incr i
    }
    set i 0
    foreach rf $rightfreqlist {
	incr k
	if {[expr $k%30]==0} {
	    if {$rightfreqArray($rf) == 1} {
		.menuBar.frequ.menu add radiobutton -label "$rf [lindex $rightfreqLabellist $i] r" \
		        -variable frequ -value [lindex $rightfreqlist $i]r -columnbreak 1 -command highlight
	    }
	} else {
	    if {$rightfreqArray($rf) == 1} {
		.menuBar.frequ.menu add radiobutton -label "$rf [lindex $rightfreqLabellist $i] r" \
		        -variable frequ -value [lindex $rightfreqlist $i]r -columnbreak 0 -command highlight
	    }
	}
	incr i
    }
    set source all
    set frequ all
    set pointsHighlighted 0
    set SDmenus_is_set 1
}

#--------------------------------------------------------------------------------------------------
# This procedure highlights points that have been selected in Source and Frequencues menus.
#--------------------------------------------------------------------------------------------------
proc highlight {} {
    global source frequ number_of_datalines dataMatrix pointsHighlighted globalxmin globalxmax globalymin globalymax
    global statuMessage
    global xitem items
    set pointsHighlighted 0
    if {($xitem=="") || ($items=="")} {
	set statusMessage "No axes selected.";
	update
	return
    }
    if {$frequ!="all"} {
	set pol [string index $frequ end]
	set frq [string range $frequ 0 [expr [string length $frequ]-2]]
    }
    for {set i 1} {$i < $number_of_datalines} {incr i} {
	if {$xitem=="Time"} {
	    set xval $dataMatrix($i,Realtime)
	} else {            
	    set xval $dataMatrix($i,$xitem)
	}
	set yval $dataMatrix($i,$items)
	if {$xval >= $globalxmin && $xval <= $globalxmax && ($yval >= $globalymin) && ($yval <= $globalymax)} {
	    .c itemconfigure point$i -fill white
	    if {$frequ=="all"} {
		if {$dataMatrix($i,Source)==$source} {
		    .c itemconfigure point$i -fill black
		    if {$dataMatrix($i,inUse)==1} {
		        incr pointsHighlighted
		    }
		}
	    } elseif {$source=="all"} {
		if {$dataMatrix($i,Frequency)==$frq && $dataMatrix($i,Polarization)==$pol} {
		    .c itemconfigure point$i -fill black
		    if {$dataMatrix($i,inUse)==1} {
		        incr pointsHighlighted
		    }
		}
	    } else {
		if {$dataMatrix($i,Source)==$source && $dataMatrix($i,Frequency)==$frq && \
		        $dataMatrix($i,Polarization)==$pol} {
		    .c itemconfigure point$i -fill black
		    if {$dataMatrix($i,inUse)==1} {
		        incr pointsHighlighted
		    }
		}
	    }
	    if {$dataMatrix($i,inUse)==0} {
		.c itemconfigure point$i -fill red
	    }
	}
    }
}

proc connect {} {
    global dataMatrix number_of_datalines xitem items pixelx pixely
    if {$xitem=="Time"} {
	set xitm "Realtime"
    } else {
	set xitm $xitem
    }
    set xlist {}
    set ylist {}
    set taglist [.c gettags current]
    set j [string range [lindex $taglist 0] 5 end]
    set currentS $dataMatrix($j,Source)
    set currentF $dataMatrix($j,Frequency)
    set currentT $dataMatrix($j,Time)
    set currentP $dataMatrix($j,Polarization)
    lappend xlist $dataMatrix($j,$xitm)
    if {$xitem!="Frequency"} {
	for {set i 1} {$i < $number_of_datalines} {incr i} {
	    if {$dataMatrix($i,inUse)==1 && $dataMatrix($i,Source)==$currentS && $dataMatrix($i,Frequency)==$currentF && \
		    $currentP==$dataMatrix($i,Polarization)} {
		lappend xlist $dataMatrix($i,$xitm)
	    }
	}
	set xlist [lsort -real $xlist]
	foreach x $xlist {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Source)==$currentS && $dataMatrix($i,Frequency)==$currentF && \
		        $x==$dataMatrix($i,$xitm) && \
		        $currentP==$dataMatrix($i,Polarization)} {
		    lappend ylist $dataMatrix($i,$items)
		    break
		}
	    }
	}
    } else {
	for {set i 1} {$i < $number_of_datalines} {incr i} {
	    if {$dataMatrix($i,inUse)==1 && $dataMatrix($i,Source)==$currentS && $dataMatrix($i,Time)==$currentT && \
		    $currentP==$dataMatrix($i,Polarization)} {
		lappend xlist $dataMatrix($i,$xitm)
	    }
	}
	set xlist [lsort -real $xlist]
	foreach x $xlist {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Source)==$currentS && $dataMatrix($i,Time)==$currentT \
		        && $x==$dataMatrix($i,$xitm) && \
		        $currentP==$dataMatrix($i,Polarization)} {
		    lappend ylist $dataMatrix($i,$items)
		    break
		}
	    }
	}
    }
    toPixels [lindex $xlist 0] [lindex $ylist 0]
    set xold $pixelx
    set yold $pixely
    for {set i 1} {$i < [llength $xlist]} {incr i} {
	toPixels [lindex $xlist $i] [lindex $ylist $i]
	set xnew $pixelx
	set ynew $pixely
	.c create line $xold $yold $xnew $ynew -tags connectCurve
	set xold $xnew
	set yold $ynew
    }
}


# ==========================================================================
#
#                             SELECTION SECTION
#
# ==========================================================================

# ---------------------------------------------------------------------------------------------
# This is the procedure that creates the "Edit" menu. It is the radiobuttons created here that 
# determines what the procedure "Replot" is actually going to plot.
# ---------------------------------------------------------------------------------------------

proc createSelectionMenu {} {
    global sourcelist detectorlist xitem items detectorArray dataMatrix number_of_datalines scaling currentRXG
    global leftfreqlist rightfreqlist leftfreqArray rightfreqArray leftfreqLabellist rightfreqLabellist 
    global currentFreq currentPol timesforsources timeAndSourceMatrix timelist currentTime statusMessage gc
    global LONamelist LOTypelist LOFirstlist LOSecondlist LOFilelist sourcetypelist leftfreqLOlist rightfreqLOlist
    global text_ready text_replot autoreplot currentW gainChoice leftincludedlist rightincludedlist
    global globalxmin globalxmax globalymin globalymax pointsIncluded
    set statusMessage "Selection menus are being created..."
    set currentPol ""
    update
    destroy .menuBar.edit.menu
    menu .menuBar.edit.menu
    .menuBar.edit.menu add cascade -label "Select Sources" -menu .menuBar.edit.menu.sources
    menu .menuBar.edit.menu.sources
    .menuBar.edit.menu add cascade -label "Left" -menu .menuBar.edit.menu.left
    menu .menuBar.edit.menu.left
    .menuBar.edit.menu add cascade -label "Right" -menu .menuBar.edit.menu.right
    menu .menuBar.edit.menu.right
    .menuBar.edit.menu add command -label "Replot (r)" -command {replot}
    .menuBar.edit.menu add cascade -label "Auto Replot" -menu .menuBar.edit.menu.auto
    .menuBar.edit.menu add separator
    .menuBar.edit.menu add command -label "Undelete All For This Selection (s)" -command showAlmostAll
    .menuBar.edit.menu add command -label "Undelete All Points In Log" -command showAll
    .menuBar.edit.menu add command -label "Delete points with bad GC" -command {deleteGCpoints}
    .menuBar.edit.menu add command -label "Delete points outside plot" -command {
	for {set i 1} {$i < $number_of_datalines} {incr i} {
	    if {(($dataMatrix($i,Polarization)=="l" && $leftfreqArray($dataMatrix($i,Frequency))==1) || \
		    ($dataMatrix($i,Polarization)=="r" && $rightfreqArray($dataMatrix($i,Frequency))==1)) && \
		    $timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1 && \
		    $dataMatrix($i,Clicked)==1 && $dataMatrix($i,inUse)==1} {
		set xval $dataMatrix($i,$xitem)
		set yval $dataMatrix($i,$items)
		if {$xval < $globalxmin || $xval > $globalxmax || $yval < $globalymin || $yval > $globalymax} {
		    set dataMatrix($i,Clicked) 0
		    set dataMatrix($i,inUse) 0
		    .c itemconfigure point$i -fill red
		    incr pointsIncluded -1
		}
	    }
	}
    }
    .menuBar.edit.menu add separator
    menu .menuBar.edit.menu.auto
    .menuBar.edit.menu.auto add radiobutton -variable autoreplot -value 1 -label "Yes"
    .menuBar.edit.menu.auto add radiobutton -variable autoreplot -value 0 -label "No"
    .menuBar.edit.menu.sources add command -label "All" -command {
	set statusMessage $text_replot
	foreach source $sourcelist {
	    foreach time $timelist {
		set timeAndSourceMatrix($time,$source) 1
	    }
	}
    }
    .menuBar.edit.menu.sources add command -label "All Calibrators" -command {
	set statusMessage $text_replot
	set i 0
	foreach sou $sourcelist {
	    if {[lindex $sourcetypelist $i]=="c"} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    }
    .menuBar.edit.menu.sources add command -label "All Calibrators & Pointing" -command {
	set statusMessage $text_replot
	set i 0
	foreach sou $sourcelist {
	    if {[lindex $sourcetypelist $i]=="c" || [lindex $sourcetypelist $i]=="p"} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    }
    .menuBar.edit.menu.sources add command -label "None" -command {
	set statusMessage $text_replot
	foreach source $sourcelist {
	    foreach time $timelist {
		set timeAndSourceMatrix($time,$source) 0
	    }
	}
    }
    .menuBar.edit.menu.sources add separator
    set currentTime ""
    set i 0
    foreach source $sourcelist {
	set sourcelabel [format "%-10s %s" $source [lindex $sourcetypelist $i]]
	.menuBar.edit.menu.sources add cascade -label "$sourcelabel" -menu .menuBar.edit.menu.sources.$source
	menu .menuBar.edit.menu.sources.$source
	bind .menuBar.edit.menu.sources.$source <Map> {
	    set currsource %W
	    set currsource [string range $currsource 27 end]
	}
	.menuBar.edit.menu.sources.$source add command -label "All" -command {
	    set statusMessage $text_replot
	    foreach time $timelist {
		if {$timesforsources($time,$currsource)==1} {
		    set timeAndSourceMatrix($time,$currsource) 1
		}
	    }
	    set currentTime "All"
	}
	.menuBar.edit.menu.sources.$source add command -label "None" -command {
	    set statusMessage $text_replot
	    foreach time $timelist {
		if {$timesforsources($time,$currsource)==1} {
		    set timeAndSourceMatrix($time,$currsource) 0
		}
	    }
	}
	.menuBar.edit.menu.sources.$source add separator
	set k 0
	foreach time $timelist {
	    if {$timesforsources($time,$source)==1} {
		incr k
		if {$k%30==0} {
		    .menuBar.edit.menu.sources.$source add checkbutton -variable timeAndSourceMatrix($time,$source) \
		            -label $time -command {set statusMessage $text_replot} -columnbreak 1
		} else {
		    .menuBar.edit.menu.sources.$source add checkbutton -variable timeAndSourceMatrix($time,$source) \
		            -label $time -command {set statusMessage $text_replot} -columnbreak 0
		}
	    }
	}
	incr i
    }
    foreach source $sourcelist {
	foreach time $timelist {
	    set timeAndSourceMatrix($time,$source) 1
	}
    }
    foreach detector $detectorlist {
	set detectorArray($detector) 1
    }
    foreach freq $rightfreqlist {
	set rightfreqArray($freq) 1
    }
    foreach freq $leftfreqlist {
	set leftfreqArray($freq) 1
    }
    .menuBar.edit.menu.left add command -label "All left" -command {
	set currentPol lcp
	set statusMessage $text_replot
	foreach freq $leftfreqlist {
	    set leftfreqArray($freq) 1
	}
    }
    .menuBar.edit.menu.left add command -label "No left" -command {
	set currentPol rcp
	set statusMessage $text_replot
	foreach freq $leftfreqlist {
	    set leftfreqArray($freq) 0
	}
    }
    .menuBar.edit.menu.left add command -label "No left or right" -command {
	set currentPol rcp
	set statusMessage $text_replot
	foreach freq $leftfreqlist {
	    set leftfreqArray($freq) 0
	}
	foreach freq $rightfreqlist {
	     set rightfreqArray($freq) 0
	 }
    }
    .menuBar.edit.menu.left add separator
    
    foreach LO $LONamelist {
	set included 0
	if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="l" && \
		        ($dataMatrix($i,LO)==[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		        $dataMatrix($i,LO)==[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	} elseif {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="l" && \
		        ($dataMatrix($i,LO)>=[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		        $dataMatrix($i,LO)<=[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	}
	if {$included==1} {
	    set j [lsearch $LONamelist $LO]
	    if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
		set delim " "
	    } else {
		set delim "-"
	    }
	    .menuBar.edit.menu.left add command -label "[lindex $LOFirstlist $j] $delim [lindex $LOSecondlist $j]" \
		-command {
		    set this [expr [$currentW index active]-5]
		    set type [lindex $LOTypelist $this]
		    set currentPol lcp
		    set fil [lindex $LOFilelist $this]
		    if {[string range $fil [expr [string length $fil]-3] end]=="rxg"} {
		        set currentRXG "[lindex $LOFilelist $this].work.$pid"
		    } else {
		        set currentRXG "[lindex $LOFilelist $this]"
		    }
		    foreach freq $leftfreqlist {
		        set leftfreqArray($freq) 0
		    }
		    foreach freq $rightfreqlist {
		        set rightfreqArray($freq) 0
		    }
		    if {$type=="range"} {
		        for {set i 1} {$i < $number_of_datalines} {incr i} {
		            if {$dataMatrix($i,Polarization)=="l" && \
		                    ($dataMatrix($i,LO)>=[lindex $LOFirstlist $this] && \
		                         $dataMatrix($i,LO)<=[lindex $LOSecondlist $this]) && \
		                    $timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1} {
		                set leftfreqArray($dataMatrix($i,Frequency)) 1
		            }
		        }
		    } elseif {$type=="fixed"} {
		        foreach freq $leftfreqlist {
		            if {[lindex $leftfreqLOlist [lsearch $leftfreqlist $freq]]==[lindex $LOFirstlist $this] || \
		                    [lindex $leftfreqLOlist [lsearch $leftfreqlist $freq]]==[lindex $LOSecondlist $this]} {
		                set leftfreqArray($freq) 1
		            }
		        }
		    }
		}
	}
    }

    .menuBar.edit.menu.left add separator
    set i 0
    set k 0
    foreach freq $leftfreqlist {
	incr k
	if {$k%30==0} {
	    .menuBar.edit.menu.left add checkbutton -variable leftfreqArray($freq) \
		    -label "[lindex $leftfreqlist $i] [lindex $leftfreqLabellist $i]" \
		    -columnbreak 1 -command {
		set currentPol lcp
		set statusMessage $text_replot
	    }
	} else {
	    .menuBar.edit.menu.left add checkbutton -variable leftfreqArray($freq) \
		    -label "[lindex $leftfreqlist $i] [lindex $leftfreqLabellist $i]" \
		    -columnbreak 0 -command {
		set currentPol lcp
		set statusMessage $text_replot
	    }
	}
	incr i
    }
    .menuBar.edit.menu.right add command -label "All right" -command {
	set currentPol rcp
	set statusMessage $text_replot
	foreach freq $rightfreqlist {
	    set rightfreqArray($freq) 1
	}
    }
    .menuBar.edit.menu.right add command -label "No right" -command {
	set currentPol lcp
	set statusMessage $text_replot
	foreach freq $rightfreqlist {
	    set rightfreqArray($freq) 0
	}
    }
    .menuBar.edit.menu.right add command -label "No right or left" -command {
	set currentPol lcp
	set statusMessage $text_replot
	foreach freq $rightfreqlist {
	    set rightfreqArray($freq) 0
	}
	foreach freq $leftfreqlist {
	    set leftfreqArray($freq) 0
	}
    }
    .menuBar.edit.menu.right add separator

    foreach LO $LONamelist {
	set included 0
	if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="r" && \
		        ($dataMatrix($i,LO)==[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		        $dataMatrix($i,LO)==[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	} elseif {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="r" && \
		        ($dataMatrix($i,LO)>=[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		        $dataMatrix($i,LO)<=[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	}
	if {$included==1} {
	    set j [lsearch $LONamelist $LO]
	    if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
		set delim " "
	    } else {
		set delim "-"
	    }
	    .menuBar.edit.menu.right add command -label "[lindex $LOFirstlist $j] $delim [lindex $LOSecondlist $j]" \
		-command {
		    set this [expr [$currentW index active]-5]
		    set type [lindex $LOTypelist $this]
		    set currentPol rcp
		    set fil [lindex $LOFilelist $this]
		    if {[string range $fil [expr [string length $fil]-3] end]=="rxg"} {
		        set currentRXG "[lindex $LOFilelist $this].work.$pid"
		    } else {
		        set currentRXG "[lindex $LOFilelist $this]"
		    }
		    foreach freq $leftfreqlist {
		        set leftfreqArray($freq) 0
		    }
		    foreach freq $rightfreqlist {
		        set rightfreqArray($freq) 0
		    }
		    if {$type=="range"} {
		        for {set i 1} {$i < $number_of_datalines} {incr i} {
		            if {$dataMatrix($i,Polarization)=="r" && \
		                    ($dataMatrix($i,LO)>=[lindex $LOFirstlist $this] && \
		                         $dataMatrix($i,LO)<=[lindex $LOSecondlist $this]) && \
		                    $timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1} {
		                set rightfreqArray($dataMatrix($i,Frequency)) 1
		            }
		        }
		    } elseif {$type=="fixed"} {
		        foreach freq $rightfreqlist {
		            if {[lindex $rightfreqLOlist [lsearch $rightfreqlist $freq]]==[lindex $LOFirstlist $this] || \
		                    [lindex $rightfreqLOlist [lsearch $rightfreqlist $freq]]==[lindex $LOSecondlist $this]} {
		                set rightfreqArray($freq) 1
		            }
		        }
		    }
		}
	}
    }
		    
    .menuBar.edit.menu.right add separator
    set i 0
    set k 0
    foreach freq $rightfreqlist {
	incr k
	if {$k%30==0} {
	    .menuBar.edit.menu.right add checkbutton -variable rightfreqArray($freq) \
		    -label "$freq [lindex $rightfreqLabellist $i]" -columnbreak 1 \
		    -command {
		set currentPol rcp
		set statusMessage $text_replot
	    }
	} else {
	    .menuBar.edit.menu.right add checkbutton -variable rightfreqArray($freq) \
		    -label "$freq [lindex $rightfreqLabellist $i]" -columnbreak 0 \
		    -command {
		set currentPol rcp
		set statusMessage $text_replot
	    }
	}
	incr i
    }
    .menuBar.edit.menu add cascade -label "Gain vs. Elev. Shortcut" -menu .menuBar.edit.menu.shortGain
    menu .menuBar.edit.menu.shortGain 
    .menuBar.edit.menu add cascade -label "TCal vs. Freq. Shortcut" -menu .menuBar.edit.menu.shortTCal
    menu .menuBar.edit.menu.shortTCal 
    .menuBar.edit.menu add cascade -label "Tsys-Tspill vs. Airmass Shortcut" -menu .menuBar.edit.menu.shortTrec
    menu .menuBar.edit.menu.shortTrec 
    .menuBar.edit.menu.shortGain add cascade -label "Left" -menu .menuBar.edit.menu.shortGain.left
    .menuBar.edit.menu.shortGain add cascade -label "Right" -menu .menuBar.edit.menu.shortGain.right
    menu .menuBar.edit.menu.shortGain.left 
    menu .menuBar.edit.menu.shortGain.right 
    .menuBar.edit.menu.shortGain.left add cascade -label "All" -menu .menuBar.edit.menu.shortGain.left.all
    menu .menuBar.edit.menu.shortGain.left.all 
    set i 0
    set k 0
    if {[llength $leftfreqlist]>0} {
	.menuBar.edit.menu.shortGain.left.all add command -label "All Frequencies" -command {
	    gainShortcutFreq left All All
	}
	incr k
	.menuBar.edit.menu.shortGain.left.all add separator
	incr k
    }
    foreach freq $leftfreqlist {
	set j [lsearch $leftfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortGain.left.all add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq left $thisFreq All
		}
	} else {
	    .menuBar.edit.menu.shortGain.left.all add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq left $thisFreq All
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortGain.left add cascade -label "All Calibrators" -menu .menuBar.edit.menu.shortGain.left.allc
    menu .menuBar.edit.menu.shortGain.left.allc 
    set i 0
    set k 0
    if {[llength $leftfreqlist]>0} {
	.menuBar.edit.menu.shortGain.left.allc add command -label "All Frequencies" -command {
	    gainShortcutFreq left All AllC
	}
	incr k
	.menuBar.edit.menu.shortGain.left.allc add separator
	incr k
    }
    foreach freq $leftfreqlist {
	set j [lsearch $leftfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortGain.left.allc add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq left $thisFreq AllC
		}
	} else {
	    .menuBar.edit.menu.shortGain.left.allc add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq left $thisFreq AllC
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortGain.left add cascade -label "All Calibrators & Pointing" -menu .menuBar.edit.menu.shortGain.left.allcp
    menu .menuBar.edit.menu.shortGain.left.allcp
    set i 0
    set k 0
    if {[llength $leftfreqlist]>0} {
	.menuBar.edit.menu.shortGain.left.allcp add command -label "All Frequencies" -command {
	    gainShortcutFreq left All AllCP
	}
	incr k
	.menuBar.edit.menu.shortGain.left.allcp add separator
	incr k
    }
    foreach freq $leftfreqlist {
	set j [lsearch $leftfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortGain.left.allcp add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq left $thisFreq AllCP
		}
	} else {
	    .menuBar.edit.menu.shortGain.left.allcp add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq left $thisFreq AllCP
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortGain.left add separator
    foreach sou $sourcelist {
	#set sourcelabel [format "%-10s %s" $sou [lindex $sourcetypelist $i]]
	.menuBar.edit.menu.shortGain.left add cascade -label "$sou" -menu .menuBar.edit.menu.shortGain.left.$sou
	menu .menuBar.edit.menu.shortGain.left.$sou 
	set i 0
	set k 0
	if {[llength $leftfreqlist]>0} {
	    .menuBar.edit.menu.shortGain.left.$sou add command -label "All Frequencies" -command {
		set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		gainShortcutFreq left All $thisSou
	    }
	    incr k
	    .menuBar.edit.menu.shortGain.left.$sou add separator
	    incr k
	}
	foreach freq $leftfreqlist {
	    set j [lsearch $leftfreqlist $freq]
	    incr k
	    if {[expr $k%30]==0} {
		.menuBar.edit.menu.shortGain.left.$sou add command -label "$freq [lindex $leftfreqLabellist $i]" \
		    -columnbreak 1 -command {
		        set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		        set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		        gainShortcutFreq left $thisFreq $thisSou
		    }
	    } else {
		.menuBar.edit.menu.shortGain.left.$sou add command -label "$freq [lindex $leftfreqLabellist $i]" \
		    -columnbreak 0 -command {
		        set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		        set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		        gainShortcutFreq left $thisFreq $thisSou
		    }
	    }
	    incr i
	}
    }
    .menuBar.edit.menu.shortGain.right add cascade -label "All" -menu .menuBar.edit.menu.shortGain.right.all
    menu .menuBar.edit.menu.shortGain.right.all 
    set i 0
    set k 0
    if {[llength $rightfreqlist]>0} {
	.menuBar.edit.menu.shortGain.right.all add command -label "All Frequencies" -command {
	    gainShortcutFreq right All All
	}
	incr k
	.menuBar.edit.menu.shortGain.right.all add separator
	incr k
    }
    foreach freq $rightfreqlist {
	set j [lsearch $rightfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortGain.right.all add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq right $thisFreq All
		}
	} else {
	    .menuBar.edit.menu.shortGain.right.all add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq right $thisFreq All
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortGain.right add cascade -label "All Calibrators" -menu .menuBar.edit.menu.shortGain.right.allc
    menu .menuBar.edit.menu.shortGain.right.allc
    set i 0
    set k 0
    if {[llength $rightfreqlist]>0} {
	.menuBar.edit.menu.shortGain.right.allc add command -label "All Frequencies" -command {
	    gainShortcutFreq right All AllC
	}
	incr k
	.menuBar.edit.menu.shortGain.right.allc add separator
	incr k
    }
    foreach freq $rightfreqlist {
	set j [lsearch $rightfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortGain.right.allc add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq right $thisFreq AllC
		}
	} else {
	    .menuBar.edit.menu.shortGain.right.allc add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq right $thisFreq AllC
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortGain.right add cascade -label "All Calibrators & Pointing" -menu .menuBar.edit.menu.shortGain.right.allcp
    menu .menuBar.edit.menu.shortGain.right.allcp
    set i 0
    set k 0
    if {[llength $rightfreqlist]>0} {
	.menuBar.edit.menu.shortGain.right.allcp add command -label "All Frequencies" -command {
	    gainShortcutFreq right All AllCP
	}
	incr k
	.menuBar.edit.menu.shortGain.right.allcp add separator
	incr k
    }
    foreach freq $rightfreqlist {
	set j [lsearch $rightfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortGain.right.allcp add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq right $thisFreq AllCP
		}
	} else {
	    .menuBar.edit.menu.shortGain.right.allcp add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq right $thisFreq AllCP
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortGain.right add separator
    foreach sou $sourcelist {
	.menuBar.edit.menu.shortGain.right add cascade -label "$sou" -menu .menuBar.edit.menu.shortGain.right.$sou
	menu .menuBar.edit.menu.shortGain.right.$sou 
	set i 0
	set k 0
	if {[llength $rightfreqlist]>0} {
	    .menuBar.edit.menu.shortGain.right.$sou add command -label "All Frequencies" -command {
		set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		gainShortcutFreq right All $thisSou
	    }
	    incr k
	    .menuBar.edit.menu.shortGain.right.$sou add separator
	    incr k
	}
	foreach freq $rightfreqlist {
	    set j [lsearch $rightfreqlist $freq]
	    incr k
	    if {[expr $k%30]==0} {
		.menuBar.edit.menu.shortGain.right.$sou add command -label "$freq [lindex $rightfreqLabellist $i]" \
		        -columnbreak 1 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		    gainShortcutFreq right $thisFreq $thisSou
		}
	    } else {
		.menuBar.edit.menu.shortGain.right.$sou add command -label "$freq [lindex $rightfreqLabellist $i]" \
		        -columnbreak 0 -command {
		    set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    gainShortcutFreq right $thisFreq $thisSou
		}
	    }
	    incr i
	}
    }
    .menuBar.edit.menu.shortTCal add cascade -label "Left" -menu .menuBar.edit.menu.shortTCal.left
    .menuBar.edit.menu.shortTCal add cascade -label "Right" -menu .menuBar.edit.menu.shortTCal.right
    menu .menuBar.edit.menu.shortTCal.left
    menu .menuBar.edit.menu.shortTCal.right
    .menuBar.edit.menu.shortTCal.left add cascade -label All -menu .menuBar.edit.menu.shortTCal.left.all
    menu .menuBar.edit.menu.shortTCal.left.all
    set leftincludedlist {}
    foreach LO $LONamelist {
	set included 0
	if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="l" && \
		        ($dataMatrix($i,LO)==[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)==[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	} elseif {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="l" && \
		        ($dataMatrix($i,LO)>=[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)<=[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	}
	if {$included==1} {
	    lappend leftincludedlist $LO
	    .menuBar.edit.menu.shortTCal.left.all add command -label "[lindex $LOFirstlist [lsearch $LONamelist $LO]] \
		    [lindex $LOSecondlist [lsearch $LONamelist $LO]]" -command {
		        set thisLO [lsearch $LONamelist [lindex $leftincludedlist [expr [$currentW index active]-1]]]
		        tcalShortcut left [lindex $LOTypelist $thisLO] $thisLO All
		    }
	}
    }
    .menuBar.edit.menu.shortTCal.left add cascade -label "All Calibrators" -menu .menuBar.edit.menu.shortTCal.left.allc
    menu .menuBar.edit.menu.shortTCal.left.allc
    set leftincludedlist {}
    foreach LO $LONamelist {
	set included 0
	if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="l" && \
		        ($dataMatrix($i,LO)==[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)==[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	} elseif {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="l" && \
		        ($dataMatrix($i,LO)>=[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)<=[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	}
	if {$included==1} {
	    lappend leftincludedlist $LO
	    .menuBar.edit.menu.shortTCal.left.allc add command -label "[lindex $LOFirstlist [lsearch $LONamelist $LO]] \
		    [lindex $LOSecondlist [lsearch $LONamelist $LO]]" -command {
		        set thisLO [lsearch $LONamelist [lindex $leftincludedlist [expr [$currentW index active]-1]]]
		        tcalShortcut left [lindex $LOTypelist $thisLO] $thisLO AllC
		    }
	}
    }
    .menuBar.edit.menu.shortTCal.left add cascade -label "All Calibrators & Pointing" -menu .menuBar.edit.menu.shortTCal.left.allcp
    menu .menuBar.edit.menu.shortTCal.left.allcp
    set leftincludedlist {}
    foreach LO $LONamelist {
	set included 0
	if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="l" && \
		        ($dataMatrix($i,LO)==[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)==[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	} elseif {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="l" && \
		        ($dataMatrix($i,LO)>=[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)<=[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	}
	if {$included==1} {
	    lappend leftincludedlist $LO
	    .menuBar.edit.menu.shortTCal.left.allcp add command -label "[lindex $LOFirstlist [lsearch $LONamelist $LO]] \
		    [lindex $LOSecondlist [lsearch $LONamelist $LO]]" -command {
		        set thisLO [lsearch $LONamelist [lindex $leftincludedlist [expr [$currentW index active]-1]]]
		        tcalShortcut left [lindex $LOTypelist $thisLO] $thisLO AllCP
		    }
	}
    }


    .menuBar.edit.menu.shortTCal.left add separator
    foreach sou $sourcelist {
	.menuBar.edit.menu.shortTCal.left add cascade -label $sou -menu .menuBar.edit.menu.shortTCal.left.$sou
	menu .menuBar.edit.menu.shortTCal.left.$sou
	set leftincludedlist {}
	foreach LO $LONamelist {
	    set included 0
	    if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
		for {set i 1} {$i < $number_of_datalines} {incr i} {
		    if {$dataMatrix($i,Polarization)=="l" && \
		            ($dataMatrix($i,LO)==[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		                 $dataMatrix($i,LO)==[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		        set included 1
		        break
		    }
		}
	    } elseif {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="range"} {
		for {set i 1} {$i < $number_of_datalines} {incr i} {
		    if {$dataMatrix($i,Polarization)=="l" && \
		            ($dataMatrix($i,LO)>=[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		                 $dataMatrix($i,LO)<=[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		        set included 1
		        break
		    }
		}
	    }
	    if {$included==1} {
		lappend leftincludedlist $LO
		.menuBar.edit.menu.shortTCal.left.$sou add command -label \
		    "[lindex $LOFirstlist [lsearch $LONamelist $LO]] \
		    [lindex $LOSecondlist [lsearch $LONamelist $LO]]" -command {
		        set thisLO [lsearch $LONamelist [lindex $leftincludedlist [expr [$currentW index active]-1]]]
		        set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		        tcalShortcut left [lindex $LOTypelist $thisLO] $thisLO $thisSou
		    }
	    }
	}
    }
    .menuBar.edit.menu.shortTCal.right add cascade -label All -menu .menuBar.edit.menu.shortTCal.right.all
    menu .menuBar.edit.menu.shortTCal.right.all
    set rightincludedlist {}
    foreach LO $LONamelist {
	set included 0
	if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="r" && \
		        ($dataMatrix($i,LO)==[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)==[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	} elseif {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="r" && \
		        ($dataMatrix($i,LO)>=[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)<=[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	}
	if {$included==1} {
	    lappend rightincludedlist $LO
	    .menuBar.edit.menu.shortTCal.right.all add command -label "[lindex $LOFirstlist [lsearch $LONamelist $LO]] \
		    [lindex $LOSecondlist [lsearch $LONamelist $LO]]" -command {
		        set thisLO [lsearch $LONamelist [lindex $rightincludedlist [expr [$currentW index active]-1]]]
		        tcalShortcut right [lindex $LOTypelist $thisLO] $thisLO All
		    }
	}
    }
    .menuBar.edit.menu.shortTCal.right add cascade -label "All Calibrators" -menu .menuBar.edit.menu.shortTCal.right.allc
    menu .menuBar.edit.menu.shortTCal.right.allc
    set rightincludedlist {}
    foreach LO $LONamelist {
	set included 0
	if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="r" && \
		        ($dataMatrix($i,LO)==[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)==[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	} elseif {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="r" && \
		        ($dataMatrix($i,LO)>=[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)<=[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	}
	if {$included==1} {
	    lappend rightincludedlist $LO
	    .menuBar.edit.menu.shortTCal.right.allc add command -label "[lindex $LOFirstlist [lsearch $LONamelist $LO]] \
		    [lindex $LOSecondlist [lsearch $LONamelist $LO]]" -command {
		        set thisLO [lsearch $LONamelist [lindex $rightincludedlist [expr [$currentW index active]-1]]]
		        tcalShortcut right [lindex $LOTypelist $thisLO] $thisLO AllC
		    }
	}
    }
    .menuBar.edit.menu.shortTCal.right add cascade -label "All Calibrators & Pointing" -menu .menuBar.edit.menu.shortTCal.right.allcp
    menu .menuBar.edit.menu.shortTCal.right.allcp
    set rightincludedlist {}
    foreach LO $LONamelist {
	set included 0
	if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="r" && \
		        ($dataMatrix($i,LO)==[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)==[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	} elseif {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="r" && \
		        ($dataMatrix($i,LO)>=[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		             $dataMatrix($i,LO)<=[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		    set included 1
		    break
		}
	    }
	}
	if {$included==1} {
	    lappend rightincludedlist $LO
	    .menuBar.edit.menu.shortTCal.right.allcp add command -label "[lindex $LOFirstlist [lsearch $LONamelist $LO]] \
		    [lindex $LOSecondlist [lsearch $LONamelist $LO]]" -command {
		        set thisLO [lsearch $LONamelist [lindex $rightincludedlist [expr [$currentW index active]-1]]]
		        tcalShortcut right [lindex $LOTypelist $thisLO] $thisLO AllCP
		    }
	}
    }
    
    .menuBar.edit.menu.shortTCal.right add separator
    foreach sou $sourcelist {
	.menuBar.edit.menu.shortTCal.right add cascade -label $sou -menu .menuBar.edit.menu.shortTCal.right.$sou
	menu .menuBar.edit.menu.shortTCal.right.$sou
	set rightincludedlist {}
	foreach LO $LONamelist {
	    set included 0
	    if {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="fixed"} {
		for {set i 1} {$i < $number_of_datalines} {incr i} {
		    if {$dataMatrix($i,Polarization)=="r" && \
		            ($dataMatrix($i,LO)==[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		                 $dataMatrix($i,LO)==[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		        set included 1
		        break
		    }
		}
	    } elseif {[lindex $LOTypelist [lsearch $LONamelist $LO]]=="range"} {
		for {set i 1} {$i < $number_of_datalines} {incr i} {
		    if {$dataMatrix($i,Polarization)=="r" && \
		            ($dataMatrix($i,LO)>=[lindex $LOFirstlist [lsearch $LONamelist $LO]] || \
		                 $dataMatrix($i,LO)<=[lindex $LOSecondlist [lsearch $LONamelist $LO]])} {
		        set included 1
		        break
		    }
		}
	    }
	    if {$included==1} {
		lappend rightincludedlist $LO
		.menuBar.edit.menu.shortTCal.right.$sou add command -label \
		    "[lindex $LOFirstlist [lsearch $LONamelist $LO]] \
		    [lindex $LOSecondlist [lsearch $LONamelist $LO]]" -command {
		        set thisLO [lsearch $LONamelist [lindex $rightincludedlist [expr [$currentW index active]-1]]]
		        set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		        tcalShortcut right [lindex $LOTypelist $thisLO] $thisLO $thisSou
		    }
	    }
	}
    }
    .menuBar.edit.menu.shortTrec add cascade -label "Left" -menu .menuBar.edit.menu.shortTrec.left
    .menuBar.edit.menu.shortTrec add cascade -label "Right" -menu .menuBar.edit.menu.shortTrec.right
    menu .menuBar.edit.menu.shortTrec.left 
    menu .menuBar.edit.menu.shortTrec.right 
    .menuBar.edit.menu.shortTrec.left add cascade -label "All" -menu .menuBar.edit.menu.shortTrec.left.all
    menu .menuBar.edit.menu.shortTrec.left.all 
    set i 0
    set k 0
    if {[llength $leftfreqlist]>0} {
	.menuBar.edit.menu.shortTrec.left.all add command -label "All Frequencies" -command {
	    trecShortcutFreq left All All
	}
	incr k
	.menuBar.edit.menu.shortTrec.left.all add separator
	incr k
    }
    foreach freq $leftfreqlist {
	set j [lsearch $leftfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortTrec.left.all add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq left $thisFreq All
		}
	} else {
	    .menuBar.edit.menu.shortTrec.left.all add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq left $thisFreq All
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortTrec.left add cascade -label "All Calibrators" -menu .menuBar.edit.menu.shortTrec.left.allc
    menu .menuBar.edit.menu.shortTrec.left.allc 
    set i 0
    set k 0
    if {[llength $leftfreqlist]>0} {
	.menuBar.edit.menu.shortTrec.left.allc add command -label "All Frequencies" -command {
	    trecShortcutFreq left All AllC
	}
	incr k
	.menuBar.edit.menu.shortTrec.left.allc add separator
	incr k
    }
    foreach freq $leftfreqlist {
	set j [lsearch $leftfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortTrec.left.allc add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq left $thisFreq AllC
		}
	} else {
	    .menuBar.edit.menu.shortTrec.left.allc add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq left $thisFreq AllC
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortTrec.left add cascade -label "All Calibrators & Pointing" -menu .menuBar.edit.menu.shortTrec.left.allcp
    menu .menuBar.edit.menu.shortTrec.left.allcp
    set i 0
    set k 0
    if {[llength $leftfreqlist]>0} {
	.menuBar.edit.menu.shortTrec.left.allcp add command -label "All Frequencies" -command {
	    trecShortcutFreq left All AllCP
	}
	incr k
	.menuBar.edit.menu.shortTrec.left.allcp add separator
	incr k
    }
    foreach freq $leftfreqlist {
	set j [lsearch $leftfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortTrec.left.allcp add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq left $thisFreq AllCP
		}
	} else {
	    .menuBar.edit.menu.shortTrec.left.allcp add command -label "$freq [lindex $leftfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq left $thisFreq AllCP
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortTrec.left add separator
    foreach sou $sourcelist {
	.menuBar.edit.menu.shortTrec.left add cascade -label "$sou" -menu .menuBar.edit.menu.shortTrec.left.$sou
	menu .menuBar.edit.menu.shortTrec.left.$sou 
	set i 0
	set k 0
	if {[llength $leftfreqlist]>0} {
	    .menuBar.edit.menu.shortTrec.left.$sou add command -label "All Frequencies" -command {
		set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		trecShortcutFreq left All $thisSou
	    }
	    incr k
	    .menuBar.edit.menu.shortTrec.left.$sou add separator
	    incr k
	}
	foreach freq $leftfreqlist {
	    set j [lsearch $leftfreqlist $freq]
	    incr k
	    if {[expr $k%30]==0} {
		.menuBar.edit.menu.shortTrec.left.$sou add command -label "$freq [lindex $leftfreqLabellist $i]" \
		    -columnbreak 1 -command {
		        set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		        set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		        trecShortcutFreq left $thisFreq $thisSou
		    }
	    } else {
		.menuBar.edit.menu.shortTrec.left.$sou add command -label "$freq [lindex $leftfreqLabellist $i]" \
		    -columnbreak 0 -command {
		        set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		        set thisFreq [lindex $leftfreqlist [expr [$currentW index active]-3]]
		        trecShortcutFreq left $thisFreq $thisSou
		    }
	    }
	    incr i
	}
    }
    .menuBar.edit.menu.shortTrec.right add cascade -label "All" -menu .menuBar.edit.menu.shortTrec.right.all
    menu .menuBar.edit.menu.shortTrec.right.all 
    set i 0
    set k 0
    if {[llength $rightfreqlist]>0} {
	.menuBar.edit.menu.shortTrec.right.all add command -label "All Frequencies" -command {
	    trecShortcutFreq right All All
	}
	incr k
	.menuBar.edit.menu.shortTrec.right.all add separator
	incr k
    }
    foreach freq $rightfreqlist {
	set j [lsearch $rightfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortTrec.right.all add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq right $thisFreq All
		}
	} else {
	    .menuBar.edit.menu.shortTrec.right.all add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq right $thisFreq All
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortTrec.right add cascade -label "All Calibrators" -menu .menuBar.edit.menu.shortTrec.right.allc
    menu .menuBar.edit.menu.shortTrec.right.allc
    set i 0
    set k 0
    if {[llength $rightfreqlist]>0} {    
	.menuBar.edit.menu.shortTrec.right.allc add command -label "All Frequencies" -command {
	    trecShortcutFreq right All AllC
	}
	incr k
	.menuBar.edit.menu.shortTrec.right.allc add separator
	incr k
    }
    foreach freq $rightfreqlist {
	set j [lsearch $rightfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortTrec.right.allc add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq right $thisFreq AllC
		}
	} else {
	    .menuBar.edit.menu.shortTrec.right.allc add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq right $thisFreq AllC
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortTrec.right add cascade -label "All Calibrators & Pointing" -menu .menuBar.edit.menu.shortTrec.right.allcp
    menu .menuBar.edit.menu.shortTrec.right.allcp
    set i 0
    set k 0
    if {[llength $rightfreqlist]>0} {    
	.menuBar.edit.menu.shortTrec.right.allcp add command -label "All Frequencies" -command {
	    trecShortcutFreq right All AllCP
	}
	incr k
	.menuBar.edit.menu.shortTrec.right.allcp add separator
	incr k
    }
    foreach freq $rightfreqlist {
	set j [lsearch $rightfreqlist $freq]
	incr k
	if {[expr $k%30]==0} {
	    .menuBar.edit.menu.shortTrec.right.allcp add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 1 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq right $thisFreq AllCP
		}
	} else {
	    .menuBar.edit.menu.shortTrec.right.allcp add command -label "$freq [lindex $rightfreqLabellist $i]" \
		-columnbreak 0 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq right $thisFreq AllCP
		}
	}
	incr i
    }
    .menuBar.edit.menu.shortTrec.right add separator
    foreach sou $sourcelist {
	.menuBar.edit.menu.shortTrec.right add cascade -label "$sou" -menu .menuBar.edit.menu.shortTrec.right.$sou
	menu .menuBar.edit.menu.shortTrec.right.$sou 
	set i 0
	set k 0
	if {[llength $rightfreqlist]>0} {
	    .menuBar.edit.menu.shortTrec.right.$sou add command -label "All Frequencies" -command {
		set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		trecShortcutFreq right All $thisSou
	    }
	    incr k
	    .menuBar.edit.menu.shortTrec.right.$sou add separator
	    incr k
	}
	foreach freq $rightfreqlist {
	    set j [lsearch $rightfreqlist $freq]
	    incr k
	    if {[expr $k%30]==0} {
		.menuBar.edit.menu.shortTrec.right.$sou add command -label "$freq [lindex $rightfreqLabellist $i]" \
		        -columnbreak 1 -command {
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		    trecShortcutFreq right $thisFreq $thisSou
		}
	    } else {
		.menuBar.edit.menu.shortTrec.right.$sou add command -label "$freq [lindex $rightfreqLabellist $i]" \
		        -columnbreak 0 -command {
		    set thisSou [lsearch $sourcelist [lindex [split $currentW .] end]]
		    set thisFreq [lindex $rightfreqlist [expr [$currentW index active]-3]]
		    trecShortcutFreq right $thisFreq $thisSou
		}
	    }
	    incr i
	}
    }
    set statusMessage $text_ready
    update
}

proc tcalShortcut {pol type index sourceindex} {
    global sourcelist timeAndSourceMatrix sourcetypelist timelist xitem items statusMessage number_of_datalines
    global leftfreqlist rightfreqlist leftfreqArray rightfreqArray hasScaled globalxmin globalxmax globalymin globalymax
    global LONamelist LOTypelist LOFirstlist LOSecondlist LOFilelist sourcetypelist leftfreqLOlist rightfreqLOlist
    global dataMatrix text_zero scaling
    set scaling Auto
    set xitem "Frequency"
    set items "TCal(K)"
    set i 0
    if {$sourceindex=="All"} {
	foreach sou $sourcelist {
	    foreach time $timelist {
		set timeAndSourceMatrix($time,$sou) 1
	    }
	}
    } elseif {$sourceindex=="AllC"} {
	set i 0
	foreach sou $sourcelist {
	    if {[lindex $sourcetypelist $i]=="c"} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    } elseif {$sourceindex=="AllCP"} {
	set i 0
	foreach sou $sourcelist {
	    if {[lindex $sourcetypelist $i]=="c" || [lindex $sourcetypelist $i]=="p"} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    } else {
	foreach sou $sourcelist {
	    if {[lindex $sourcelist $sourceindex]==$sou} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    }
    foreach freq $leftfreqlist {
	set leftfreqArray($freq) 0
    }
    foreach freq $rightfreqlist {
	set rightfreqArray($freq) 0
    }
    if {$pol=="left"} {
	if {$type=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="l" && \
		        ($dataMatrix($i,LO)>=[lindex $LOFirstlist $index] && \
		        $dataMatrix($i,LO)<=[lindex $LOSecondlist $index]) && \
		        $timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1} {
		    set leftfreqArray($dataMatrix($i,Frequency)) 1
		}
	    }
	} elseif {$type=="fixed"} {
	    foreach freq $leftfreqlist {
		if {[lindex $leftfreqLOlist [lsearch $leftfreqlist $freq]]==[lindex $LOFirstlist $index] || \
		        [lindex $leftfreqLOlist [lsearch $leftfreqlist $freq]]==[lindex $LOSecondlist $index]} {
		    set leftfreqArray($freq) 1
		}
	    }
	}
    } elseif {$pol=="right"} {
	if {$type=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,Polarization)=="r" && \
		        ($dataMatrix($i,LO)>=[lindex $LOFirstlist $index] && \
		        $dataMatrix($i,LO)<=[lindex $LOSecondlist $index]) && \
		        $timeAndSourceMatrix($dataMatrix($i,Time),$dataMatrix($i,Source)) == 1} {
		    set rightfreqArray($dataMatrix($i,Frequency)) 1
		}
	    }
	} elseif {$type=="fixed"} {
	    foreach freq $rightfreqlist {
		if {[lindex $rightfreqLOlist [lsearch $rightfreqlist $freq]]==[lindex $LOFirstlist $index] || \
		        [lindex $rightfreqLOlist [lsearch $rightfreqlist $freq]]==[lindex $LOSecondlist $index]} {
		    set rightfreqArray($freq) 1
		}
	    }
	}
    }
    for {set i 1} {$i < $number_of_datalines} {incr i} {
	if {$dataMatrix($i,Clicked)==1} {
	    set dataMatrix($i,inUse) 1
	}
    }
    set hasScaled 0
    autoScale
    destroy .scaleWindow  
    if {$globalxmin!=$globalxmax && $globalymin!=$globalymax} {
	replot
    } else {
	set statusMessage $text_zero
    }
}


proc gainShortcutFreq {pol thisFreq sourceindex} {
    global sourcelist timeAndSourceMatrix sourcetypelist timelist hasScaled statusMessage xitem items gainChoice scaling
    global leftfreqlist rightfreqlist leftfreqArray rightfreqArray globalxmin globalxmax globalymin globalymax text_zero
    set scaling Auto
    set xitem "Elevation"
    set items "Gain"
    if {![info exists gainChoice] || $gainChoice==0 || $gainChoice==""} {
	set gainChoice 1
    }
    set i 0
    if {$sourceindex=="All"} {
	foreach sou $sourcelist {
	    foreach time $timelist {
		set timeAndSourceMatrix($time,$sou) 1
	    }
	}
    } elseif {$sourceindex=="AllC"} {
	set i 0
	foreach sou $sourcelist {
	    if {[lindex $sourcetypelist $i]=="c"} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    } elseif {$sourceindex=="AllCP"} {
	set i 0
	foreach sou $sourcelist {
	    if {[lindex $sourcetypelist $i]=="c" || [lindex $sourcetypelist $i]=="p"} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    } else {
	foreach sou $sourcelist {
	    if {[lindex $sourcelist $sourceindex]==$sou} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    }
    foreach freq $leftfreqlist {
	set leftfreqArray($freq) 0
    }
    foreach freq $rightfreqlist {
	set rightfreqArray($freq) 0
    }
    if {$thisFreq=="All"} {
	if {$pol=="left"} {
	    foreach freq $leftfreqlist {
		set leftfreqArray($freq) 1
	    }
	} elseif {$pol=="right"} {
	    foreach freq $rightfreqlist {
		set rightfreqArray($freq) 1
	    }
	}
    } else {
	if {$pol=="left"} {
	    set leftfreqArray($thisFreq) 1
	}
	if {$pol=="right"} {
	    set rightfreqArray($thisFreq) 1
	}
    }
    set hasScaled 0
    autoScale
    destroy .scaleWindow  
    if {$globalxmin!=$globalxmax && $globalymin!=$globalymax} {
	replot
    } else {
	set statusMessage $text_zero
    }
}

proc trecShortcutFreq {pol thisFreq sourceindex} {
    global sourcelist timeAndSourceMatrix sourcetypelist timelist hasScaled statusMessage xitem items scaling
    global leftfreqlist rightfreqlist leftfreqArray rightfreqArray globalxmin globalxmax globalymin globalymax text_zero
    set scaling Auto
    set xitem "Airmass"
    set items "Tsys-Tspill"
    set i 0
    if {$sourceindex=="All"} {
	foreach sou $sourcelist {
	    foreach time $timelist {
		set timeAndSourceMatrix($time,$sou) 1
	    }
	}
    } elseif {$sourceindex=="AllC"} {
	set i 0
	foreach sou $sourcelist {
	    if {[lindex $sourcetypelist $i]=="c"} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    } elseif {$sourceindex=="AllCP"} {
	set i 0
	foreach sou $sourcelist {
	    if {[lindex $sourcetypelist $i]=="c" || [lindex $sourcetypelist $i]=="p"} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    } else {
	foreach sou $sourcelist {
	    if {[lindex $sourcelist $sourceindex]==$sou} {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 1
		}
	    } else {
		foreach time $timelist {
		    set timeAndSourceMatrix($time,$sou) 0
		}
	    }
	    incr i
	}
    }
    foreach freq $leftfreqlist {
	set leftfreqArray($freq) 0
    }
    foreach freq $rightfreqlist {
	set rightfreqArray($freq) 0
    }
    if {$thisFreq=="All"} {
	if {$pol=="left"} {
	    foreach freq $leftfreqlist {
		set leftfreqArray($freq) 1
	    }
	} elseif {$pol=="right"} {
	    foreach freq $rightfreqlist {
		set rightfreqArray($freq) 1
	    }
	}
    } else {
	if {$pol=="left"} {
	    set leftfreqArray($thisFreq) 1
	}
	if {$pol=="right"} {
	    set rightfreqArray($thisFreq) 1
	}
    }
    set hasScaled 0
    autoScale
    destroy .scaleWindow  
    if {$globalxmin!=$globalxmax && $globalymin!=$globalymax} {
	replot
    } else {
	set statusMessage $text_zero
    }
}


# ----------------------------------------------------------------------------------------
# The following two procedures toggles points between "on" and "off" when the user clicks
# on them. The first one toggles just the point the user clicked on and runs when the user
# left-clicks on a point. The second one is run when the user right-clicks on a point, and
# toggles all points with the same time value between "on" and "off".
# ----------------------------------------------------------------------------------------

proc togglePoint {} {
    global dataMatrix items BADVALUE pointsIncluded
    set taglist [.c gettags current]
    set i [string range [lindex $taglist 0] 5 end]
    if {$dataMatrix($i,inUse)==1} {
	#if {$dataMatrix($i,Clicked)==1} {}
	set dataMatrix($i,inUse) 0
	set dataMatrix($i,Clicked) 0
	incr pointsIncluded -1
	.c itemconfigure point$i -fill red
    } elseif {$dataMatrix($i,$items)>$BADVALUE} {
	.c itemconfigure point$i -fill white
	set dataMatrix($i,inUse) 1
	set dataMatrix($i,Clicked) 1
	incr pointsIncluded
    }
}



proc toggleManyPoints {} {
    global dataMatrix number_of_datalines timeAndSourceMatrix items BADVALUE pointsIncluded
    set taglist [.c gettags current]
    set nodeNumber [string range [lindex $taglist 0] 5 end]
    set time $dataMatrix($nodeNumber,Time)
    set inUse $dataMatrix($nodeNumber,inUse)
    for {set i 1} {$i < $number_of_datalines} {incr i} {
	if {$dataMatrix($i,Time)==$time} {
	    if {$inUse} {
		set dataMatrix($i,inUse) 0
		set dataMatrix($i,Clicked) 0
		incr pointsIncluded -1
		.c itemconfigure point$i -fill red
	    } elseif {$dataMatrix($i,$items)>$BADVALUE} {
		set dataMatrix($i,inUse) 1
		set dataMatrix($i,Clicked) 1
		incr pointsIncluded
		.c itemconfigure point$i -fill white
	    }
	}
    }
}


proc toggleTrec {} {
    global trecmarkerlist
    set taglist [.c gettags current]
    set nodeNumber [string range [lindex $taglist 0] 10 end]
    set i $nodeNumber
    if {[lindex $trecmarkerlist $i]==0} {
	set trecmarkerlist [lreplace $trecmarkerlist $i $i 1]
	.c itemconfigure trecmarker$i -fill white
    } elseif {[lindex $trecmarkerlist $i]==1} {
	set trecmarkerlist [lreplace $trecmarkerlist $i $i 0]
	.c itemconfigure trecmarker$i -fill red
    }
}

# -----------------------------------------------------------------------------------
# This procedure deletes the points with a gain compression outside the allowed range
# The factor makes sure that both logs where the gain compression is given in percent
# as well as logs where the gain compression is given in unity works. The variable
# 'corr' corrects for the points with "bad" values.
# -----------------------------------------------------------------------------------

proc deleteGCpoints {} {
    global dataMatrix number_of_datalines timeAndSourceMatrix
    toplevel .gcWindow
    wm title .gcWindow "Gain Compression Limits"
    frame .gcWindow.lower
    frame .gcWindow.upper
    frame .gcWindow.buttons
    label .gcWindow.lower.label -text "Lower limit:"
    label .gcWindow.upper.label -text "Upper limit:"
    entry .gcWindow.lower.entry -width 8 -relief sunken -textvariable lowerGC
    entry .gcWindow.upper.entry -width 8 -relief sunken -textvariable upperGC
    button .gcWindow.buttons.ok -text "OK" -command {
	set gcl "Gain Compression"
	set test 0
	set corr 0
	#If the user has entered GC in percent, this sets it back to unity
	if {$lowerGC>10} {
	    set realLowerGC [expr double($lowerGC)/100]
	    set realUpperGC [expr double($upperGC)/100]
	} else {
	    set realLowerGC $lowerGC
	    set realUpperGC $upperGC
	}
	for {set i 1} {$i < $number_of_datalines} {incr i} {
	    if {$dataMatrix($i,$gcl)>0 && $dataMatrix($i,$gcl)<1000} {
		set test [expr $test+$dataMatrix($i,$gcl)]
	    } else {
		incr corr
	    }
	}
	if {[expr $test/($number_of_datalines-$corr)]>10} {
	    set factor 100
	} else {
	    set factor 1
	}
	for {set i 1} {$i < $number_of_datalines} {incr i} {
	    if {$dataMatrix($i,$gcl)<[expr $realLowerGC*$factor] || $dataMatrix($i,$gcl)>[expr $realUpperGC*$factor]} {
		set dataMatrix($i,inUse) 0
		set dataMatrix($i,Clicked) 0
		.c itemconfigure point$i -fill red
		set test 1
	    }
	}
	destroy .gcWindow
	replot
    }
    button .gcWindow.buttons.cancel -text "Cancel" -command {
	destroy .gcWindow
    }
    pack .gcWindow.lower.label .gcWindow.lower.entry -side left -in .gcWindow.lower
    pack .gcWindow.upper.label .gcWindow.upper.entry -side left -in .gcWindow.upper
    pack .gcWindow.buttons.ok .gcWindow.buttons.cancel -side left -in .gcWindow.buttons
    pack .gcWindow.lower .gcWindow.upper .gcWindow.buttons -side top -in .gcWindow
}




# ==========================================================================
#
#                               TOOLS SECTION
#
# ==========================================================================

#MC:AO known bug: if two entries are outside plot area and their slope is 0 then a 
# stright line is drawn
# -------------------------------------------------------------------------------------
# This procedure creates the "Tools" menu and changes it according to what the user has
# currently selected. For example it draws the Tcal vs. Frequency curve, and also sends
# the current gain curve to the procedure "drawPoly".
# -------------------------------------------------------------------------------------
proc curveinFile tckmenu {
    global items sourcelist fitchoice currentPol currentRXG pixelx pixely number_of_LO number_of_pol pointoffplot gctype
    global fctk statusMessage fgc thickline dataMatrix xoffset pointoffplot globalxmin globalxmax globalymin globalymax
    global hourint opacityCorrect fittedtrecmark avgtrec trecmarkerlist trecfitlist minvalue maxvalue timeinseconds
    global opacityCurveCorrect trecsigmafitlist thickline 
    if {$tckmenu==1} {
	set fileID [open $currentRXG r]
	set k 1
	set xlist {}
	set ylist {}
	set finish 0
	while {-1 != [gets $fileID line]} {
	    if {[string index $line 0] != "\*"} {
		if {$line=="end_tcal_table"} {
		    set finish 1
		}
		if {$k>=7 && $finish==0} {
		    split $line
		    if {[lindex $line 0]==$currentPol} {
		        lappend xlist [lindex $line 1]
		        lappend ylist [lindex $line 2]
		    }
		 }
		 incr k
	    }
	}
	close $fileID
	#MC:AO Piece of code rewritten because cases NN=0 and NN=1 were not correctly handled. 
	#       routine rewritten in a more compact and clear fashion.
	set NN [llength $xlist]
	if {$NN==0} {
	    set statusMessage "No Tcal table defined for this polarization"
	} elseif {$NN==1} {
	    # this draws a straight line y=[lindex $ylist 0]
	    set xstart $globalxmin
	    set xstop $globalxmax
	    set ystart [lindex $ylist 0]
	    set ystop $ystart
	    toPixels $xstart $ystart
	    set pixelxstart $pixelx
	    set pixelystart $pixely
	    toPixels $xstop $ystop
	    set pixelxstop $pixelx
	    set pixelystop $pixely
	    drawTCalCurve $xstart $ystart $xstop $ystop tcalcurve
	} else {
	    for {set i 0} {$i<[expr $NN-1]} {incr i} {
		set datapoints {}
		set m [expr ([lindex $ylist $i]-[lindex $ylist [expr $i+1]])/ \
		        ([lindex $xlist $i]-[lindex $xlist [expr $i+1]])]
		set k [expr [lindex $ylist $i]-$m*[lindex $xlist $i]]
		# this take charge of matching the left edge
		if {$i==0 && [lindex $xlist $i]>$globalxmin} {
		        set datapoints "$datapoints { [expr $globalxmin*$m+$k] $globalxmin }"
		} else {
		        set datapoints "$datapoints { [lindex $ylist $i] [lindex $xlist $i] }"
		}
		# this take charge of matching the right edge
		if {$i==[expr $NN-2] && [lindex $xlist [expr $i+1]]<$globalxmax} {
		    set datapoints "$datapoints { [expr $globalxmax*$m+$k] $globalxmax }"
		} else {
		    set datapoints "$datapoints { [lindex $ylist [expr $i+1]] [lindex $xlist [expr $i+1]] }"
		}
		# intersections with the edges
		set datapoints "$datapoints { [expr $globalxmin*$m+$k] $globalxmin }"
		set datapoints "$datapoints { [expr $globalxmax*$m+$k] $globalxmax }"
		if {$m!=0} {
		    set datapoints "$datapoints { $globalymin [expr ($globalymin-$k)/$m] }"
		    set datapoints "$datapoints { $globalymax [expr ($globalymax-$k)/$m] }"
		    set datapoints [lsort -real -index 0 $datapoints]
		    #take the 2 inner points....draw a line between them
		    set xstart [lindex [lindex $datapoints 2] 1]
		    set ystart [lindex [lindex $datapoints 2] 0]
		    set xstop [lindex [lindex $datapoints 3] 1]
		    set ystop [lindex [lindex $datapoints 3] 0]
		} else {
		    set datapoints [lsort -real -index 1 $datapoints]
		    #take the 2 inner points....draw a line between them
		    set xstart [lindex [lindex $datapoints 1] 1]
		    set ystart [lindex [lindex $datapoints 1] 0]
		    set xstop [lindex [lindex $datapoints 2] 1]
		    set ystop [lindex [lindex $datapoints 2] 0]
		}
		if {$xstart>=$globalxmin && $xstart<=$globalxmax && $ystart>=$globalymin && $ystart<=$globalymax} {
		    if {$xstop>=$globalxmin && $xstop<=$globalxmax && $ystop>=$globalymin && $ystop<=$globalymax} {
		        drawTCalCurve $xstart $ystart $xstop $ystop tcalcurve
		    }
		}
	    }
	} 
		        #if {[llength $xlist]==2 && [lindex $xlist 0]<$globalxmin && [lindex $xlist 1]>$globalxmax} {
		        #    set k [expr ([lindex $ylist 1]-[lindex $ylist 0])/([lindex $xlist 1]-[lindex $xlist 0])]
		        #    set m [expr [lindex $ylist 1]-$k*[lindex $xlist 1]]
		        #    set xstart $globalxmin
		        #    set xstop $globalxmax
		        #    set ystart [expr $k*$xstart+$m]
		        #    set ystop [expr $k*$xstop+$m]
		        #    toPixels $xstart $ystart
		        #    set pixelxstart $pixelx
		        #    set pixelystart $pixely
		        #    toPixels $xstop $ystop
		        #    set pixelxstop $pixelx
		        #    set pixelystop $pixely
		        #    .c create line $pixelxstart $pixelystart $pixelxstop $pixelystop \
		        #            -tags tcalcurve -fill green3 -width $thickline
		        #} else {
		        #    for {set i 0} {$i<[expr [llength $xlist]-1]} {incr i} {
		        #        if {[lindex $xlist $i]<$globalxmin || [lindex $xlist [expr $i+1]]>$globalxmax} { 
		        #        } elseif {[lindex $ylist [expr $i+1]]>=$globalymin && \
		        #                [lindex $ylist [expr $i+1]]<=$globalymax} {
		        #            drawTCalCurve [lindex $xlist $i] [lindex $ylist $i] [lindex $xlist [expr $i+1]] \
		        #                    [lindex $ylist [expr $i+1]] tcalcurve
		        #        }
		        #    }
		        #}
		        #Check edges match:
		        #if {[lsearch $xlist $globalxmin]==-1} {
		        #    set i 0
		        #    foreach x $xlist {
		        #       if {$x>$globalxmin} {
		        #            break
		        #        }
		        #        incr i
		        #    }
		        #    if {$i==0} {
		        #        set xstart $globalxmin
		        #        set xstop [lindex $xlist $i]
		        #        set ystart [lindex $ylist $i]
		        #        set ystop [lindex $ylist $i]
		        #    } else {
		        #        set k [expr ([lindex $ylist $i]-[lindex $ylist [expr $i-1]])/([lindex $xlist $i]-[lindex $xlist [expr $i-1]])]
		        #        set m [expr [lindex $ylist $i]-$k*[lindex $xlist $i]]
		        #        set xstart $globalxmin
		        #        set xstop [lindex $xlist $i]
		        #        set ystart [lindex $ylist $i]
		        #        set ystop [expr $k*$xstop+$m]
		        #    }
		        #    toPixels $xstart $ystart
		        #    set pixelxstart $pixelx
		        #    set pixelystart $pixely
		        #    toPixels $xstop $ystop
		        #    set pixelxstop $pixelx
		        #    set pixelystop $pixely
		        #    .c create line $pixelxstart $pixelystart $pixelxstop $pixelystop \
		        #            -tags tcalcurve -fill green3 -width $thickline
		        #}
		        #if {[lsearch $xlist $globalxmax]==-1} {
		        #    set i 0
		        #    foreach x $xlist {
		        #        if {$x>$globalxmax} {
		        #            break
		        #        }
		        #        incr i
		        #    }
		        #    incr i -1 ;#one step back needed, i is the first element outside the plot
		        #    if {$i==[expr [llength $xlist]+1]} {
		        #        set xstart [lindex $xlist $i]
		        #        set xstop $globalxmax
		        #        set ystart [lindex $ylist $i]
		        #        set ystop [lindex $ylist $i]
		        #    } else {
		        #       set k [expr ([lindex $ylist [expr $i+1]]-[lindex $ylist $i])/([lindex $xlist [expr $i+1]]-[lindex $xlist $i])]
		        #       set m [expr [lindex $ylist $i]-$k*[lindex $xlist $i]]
		        #       set xstart [lindex $xlist $i]
		        #        set xstop $globalxmax
		        #        set ystart [lindex $ylist $i]
		        #        set ystop [expr $k*$xstop+$m]
		        #    }
		        #    toPixels $xstart $ystart
		        #    set pixelxstart $pixelx
		        #    set pixelystart $pixely
		        #    toPixels $xstop $ystop
		        #    set pixelxstop $pixelx
		        #    set pixelystop $pixely
		        #    .c create line $pixelxstart $pixelystart $pixelxstop $pixelystop \
		        #            -tags tcalcurve -fill green3 -width $thickline
		        #}
    #MC:AO typo eliminated. this caused the curve not to be eliminated
    } elseif {$tckmenu==0} {
	.c delete tcalcurve
    }
}


proc createToolsMenu xitem {
    global items sourcelist fitchoice currentPol currentRXG pixelx pixely number_of_LO number_of_pol pointoffplot gctype
    global fctk statusMessage fgc thickline dataMatrix xoffset pointoffplot globalxmin globalxmax globalymin globalymax
    global hourint opacityCorrect fittedtrecmark avgtrec trecmarkerlist trecfitlist minvalue maxvalue timeinseconds
    global opacityCurveCorrect trecsigmafitlist thickline 
    destroy .menuBar.tools.menu
    menu .menuBar.tools.menu
    if {$items=="TCal Ratio" || $items=="Gain Compression"} {
	.menuBar.tools.menu add checkbutton -variable tcr -label "Draw line at 1" -command {
	    if {$tcr==1} {
		set gcl "Gain Compression"
		set test 0
		set corr 0
		#If the user has entered GC in percent, this sets it back to unity
		if {$items=="TCal Ratio"} {
		    set factor 1
		} else {
		    for {set i 1} {$i < $number_of_datalines} {incr i} {
		        if {$dataMatrix($i,$gcl)>0 && $dataMatrix($i,$gcl)<5000} {
		            set test [expr $test+$dataMatrix($i,$gcl)]
		        } else {
		            incr corr
		        }
		    }
		    if {[expr $test/($number_of_datalines-$corr)]>10} {
		        set factor 100
		    } else {
		        set factor 1
		    }
		}
		toPixels $globalxmin [expr 1*$factor]
		set pixelxmin $pixelx
		set pixelymin $pixely   
		toPixels $globalxmax [expr 1*$factor]
		set pixelxmax $pixelx
		set pixelymax $pixely   
		.c create line $pixelxmin $pixelymin $pixelxmax $pixelymax -tags tcrcurve 
	    } elseif {$tcr==0} {
		.c delete tcrcurve
	    }
	}
    }
    if {$xitem=="Elevation"} {
	if {$number_of_LO==1 && $number_of_pol==1 && $currentRXG != ""} {
	    if {[string match Gain $items]} {
		.menuBar.tools.menu add checkbutton -label "Gain Curve in working file" -variable gc -command {
		    if {$gc==1} {
		        set fileID [open $currentRXG r]
		        set k 1
		        while {-1 != [gets $fileID line]} {
		            if {[string index $line 0] != "\*"} {
		                if {$k==4} {
		                    split $line
		                    if {[llength $line] > 1} {
		                        if {[lindex $line 0]==$currentPol} {set right 0}
		                        if {[lindex $line 1]==$currentPol} {set right 1}
		                    } else {
		                        set right -1
		                    }
		                }
		                if {$k==5} {
		                    split $line
		                    if {$right==-1} {
		                        set DPFU [lindex $line 0]
		                    } else {
		                        set DPFU [lindex $line $right]
		                    }
		                }
		                if {$k==6} {
		                    if {![info exists gctype]} {
		                        set gctype [lindex $line 0]
		                    }
		                    split $line
		                    if {[lindex $line end]=="opacity_correct"} {
		                        set gainlist [lrange $line 0 [expr [llength $line]-2]]
		                        set opacityCurveCorrect 1
		                        if {$opacityFlag==1} {
		                            .c itemconfigure opacityHeader -text "Opacity corrected data and gain curve"
		                        } else {
		                            .c itemconfigure opacityHeader -text "Opacity corrected gain curve"
		                        }
		                    } else {
		                        set gainlist $line
		                        if {$opacityCorrect==1} {
		                            .c itemconfigure opacityHeader -text "Opacity corrected data"
		                        } else {
		                            .c itemconfigure opacityHeader -text ""
		                        }
		                    }
		                }
		                incr k
		            }
		        }
		        close $fileID
		        drawPoly $DPFU [lreplace $gainlist 0 1] gaincurve $gctype nodash green3
		    } elseif {$gc==0} {
		        .c delete gaincurve
		    }
		}
		.menuBar.tools.menu add checkbutton -label "Fitted Gain Curve" -variable fgc -command {
		    if {$fgc==0} {
		        .c delete fittedgaincurve
		    } elseif {$fgc==1} {
		        set statusMessage " Turn on the fitted curve by refitting"
		    }
		}
		.menuBar.tools.menu add cascade -label "Fit to" -menu .menuBar.tools.menu.fit
		menu .menuBar.tools.menu.fit
		.menuBar.tools.menu.fit add radiobutton -label "New DPFU" \
		    -command {outputFit 1} -variable fitChoice -value 1
		.menuBar.tools.menu.fit add radiobutton -label "Gain Curve and DPFU" \
		    -command {outputFit 2} -variable fitChoice -value 2
		.menuBar.tools.menu.fit add radiobutton -label "Scale TCal(K)" \
		    -command {outputFit 3} -variable fitChoice -value 3
		.menuBar.tools.menu add command -label "Update Working File" -command {
		    updateRXGwithfit $fitChoice
		    .menuBar.tools.menu invoke *file
		}
		.menuBar.tools.menu add separator
	    }
	} elseif {$items=="Gain"} {
	    if {$number_of_LO==1 && $currentRXG!=""} {
		.menuBar.tools.menu add command -label "Please select polarization"
	    } elseif {$number_of_pol==1} {
		.menuBar.tools.menu add command -label "Please select LO"
	    } else {
		.menuBar.tools.menu add command -label "Please select both LO & Pol"
	    }
	}
    }
    if {$xitem=="Frequency"} {
	if {[string match $items TCal(K)]} {
	    if {$number_of_LO==1 && $number_of_pol==1 && $currentRXG != ""} {
		.menuBar.tools.menu add checkbutton -label "TCal(K) Curve in file" -variable tck -command {
		    curveinFile $tck
		}
		.menuBar.tools.menu add checkbutton -label "Fitted TCal(K) Curve" -variable ftck -command {
		    if {$ftck==0} {
		        .c delete fittedtcalcurve
		    } elseif {$ftck==1} {
		        set statusMessage "Turn on the fitted curve by refitting"
		        set ftck 0
		    }
		}
		.menuBar.tools.menu add separator
		.menuBar.tools.menu add cascade -label "Fit for TCal(K)" -menu .menuBar.tools.menu.fit
		menu .menuBar.tools.menu.fit    
		.menuBar.tools.menu.fit add command -label "Average at each freq." -command {fitForTCal 1}
		.menuBar.tools.menu.fit add command -label "Median at each freq." -command {fitForTCal 2}
		.menuBar.tools.menu add command -label "Update Working file" -command {
		    updateRXGwithTCal
		}
	    } else {
		if {$number_of_LO==1 && $currentRXG!=""} {
		    .menuBar.tools.menu add command -label "Please select polarization"
		} elseif {$number_of_pol==1} {
		    .menuBar.tools.menu add command -label "Please select LO"
		} else {
		    .menuBar.tools.menu add command -label "Please select both LO & Pol"
		}
	    }
	}
    }
    if {$xitem=="Airmass"} {
	if {$items=="Tsys-Tspill"} {
	    .menuBar.tools.menu add checkbutton -label "Mark Trec from file" -variable trecmark -command {
		set trec 0
		if {$trecmark==1} {
		    for {set i 1} {$i < $number_of_datalines} {incr i} {
		        if {$dataMatrix($i,inUse)==1} {
		            set trec $dataMatrix($i,Trec)
		            break
		        }
		    }
		    if {$trec>=$globalymin && $trec <=$globalymax && $trec!=0} {
		        set r 4
		        toPixels 0 $trec
		        set x $pixelx
		        set y $pixely
		        .c create oval [expr $x-$r] [expr $y-$r] [expr $x+$r] [expr $y+$r] \
		            -fill green3 -tags trecmarker -width 1
		        .c create text [expr $x-[string length $trec]*6] $y -text $trec -tags trecmarker
		        .c create line [expr $xoffset-10] $y [expr $xoffset-$pointoffplot] $y -tags trecmarker
		    } elseif {$trec==0} {
		        set statusMessage "No trec in file"
		        set trecmark 0
		    } else {
		        set statusMessage "Trec in file outside of current range (Trec=$trec)"
		    }
		} else {
		    .c delete trecmarker
		    set statusMessage "Ready."
		}
	    }
	    .menuBar.tools.menu add checkbutton -label "Mark fitted Trec" -variable fittedtrecmark -command {
		if {$fittedtrecmark==1} {
		    if {[info exists avgtrec]} { 
		        if {$avgtrec>=$globalymin && $avgtrec <=$globalymax && $avgtrec!=0} {
		            set r 4
		            toPixels 0 $avgtrec
		            set x $pixelx
		            set y $pixely
		            .c create oval [expr $x-$r] [expr $y-$r] [expr $x+$r] [expr $y+$r] \
		                    -fill black -tags fittedtrecmarkaverage -width 1
		            .c create text [expr $x-[string length $avgtrec]*6] $y \
		                    -text $avgtrec -tags fittedtrecmarkaverage
		            .c create line [expr $xoffset-10] $y [expr $xoffset-$pointoffplot] $y \
		                    -tags fittedtrecmarkaverage
		        }
		    } else {
		        set statusMessage "No fit available."
		        set fittedtrecmark 0
		    }                    
		} else {
		    .c delete fittedtrecmarkaverage
		    set statusMessage "Ready."
		}
	    }
	}
	.menuBar.tools.menu add separator
	#fit for receiver temperature. A time interval is requested where the Tatm is supposed stable
	.menuBar.tools.menu add command -label "Fit for Trec" -command {
	    min Time
	    max Time
	    set timemin $minvalue
	    set timemax $maxvalue
	    time2sec $timemin
	    set realtimemin $timeinseconds
	    time2sec $timemax
	    set realtimemax $timeinseconds
	    set range [expr $realtimemax-$realtimemin]
	    toplevel .trecintChoice
	    wm title .trecintChoice "Select Interval and Tatm"
	    frame .trecintChoice.frame0
	    frame .trecintChoice.frame1
	    frame .trecintChoice.frame2
	    frame .trecintChoice.frame3
	    label .trecintChoice.header0 -text "Please select Tatm (°K):"
	    label .trecintChoice.header -text "Please select time interval for fit:"
	    entry .trecintChoice.entry0 -width 3 -textvariable tatm
	    entry .trecintChoice.entry -width 3 -textvariable hourint
	    label .trecintChoice.hour -text "hours"
	    label .trecintChoice.total -text "Total time range of selected points:"
	    label .trecintChoice.total2 -text "[expr int(floor($range/3600))]hours, \
		    [expr int(($range-floor($range/3600)*3600)/60)]minutes"
	    button .trecintChoice.ok -text "OK" -command {
		fitForTrec
		destroy .trecintChoice
	    }
	    button .trecintChoice.cancel -text "Cancel" -command {
		destroy .trecintChoice
	    }
	    pack .trecintChoice.header0 .trecintChoice.entry0 -in .trecintChoice.frame0 \
		-side left -padx 3m -fill x
	    pack .trecintChoice.header .trecintChoice.entry .trecintChoice.hour -in .trecintChoice.frame1 \
		-side left -padx 3m -fill x
	    pack .trecintChoice.total .trecintChoice.total2 -in .trecintChoice.frame2 \
		-side left -padx 2m -fill x
	    pack .trecintChoice.ok .trecintChoice.cancel -in .trecintChoice.frame3 \
		-side left -ipadx 2m 
	    pack .trecintChoice.frame0 .trecintChoice.frame1 .trecintChoice.frame2 .trecintChoice.frame3 \
		    -in .trecintChoice -anchor center -side top -pady 1m 
	}
	.menuBar.tools.menu add command -label "Recalculate Trec" -command {
	    if {[info exists trecfitlist]} {
		.c delete fittedtrecmarkaverage
		set sum 0
		set inc 0
		set sigmasum 0
		for {set i 0} {$i<[llength $trecfitlist]} {incr i} {
		    if {[lindex $trecmarkerlist $i]==1} {
		        set sum [expr $sum+[lindex $trecfitlist $i]/pow([lindex $trecsigmafitlist $i],2)]
		        set sigmasum [expr $sigmasum+1/pow([lindex $trecsigmafitlist $i],2)]
		    }
		}
		set avgtrec [format %.3f [expr $sum/$sigmasum]]
		if {$avgtrec>=$globalymin && $avgtrec <=$globalymax && $avgtrec!=0} {
		    set r 4
		    toPixels 0 $avgtrec
		    set x $pixelx
		    set y $pixely
		    .c create oval [expr $x-$r] [expr $y-$r] [expr $x+$r] [expr $y+$r] \
		        -fill black -tags fittedtrecmarkaverage -width 1
		    .c create text [expr $x-[string length $avgtrec]*6] $y -text $avgtrec -tags fittedtrecmarkaverage
		    .c create line [expr $xoffset-10] $y [expr $xoffset-$pointoffplot] $y -tags fittedtrecmarkaverage
		    set fittedtrecmark 1
		}
	    } else {
		set statusMessage "Can't recalculate. No fit available."
	    }
	}
	.menuBar.tools.menu add separator
	.menuBar.tools.menu add command -label "Update working file" -command {
	    if {[info exists avgtrec]} {
		updateRXGwithTrec $avgtrec
	    }
	}
	.menuBar.tools.menu add separator
	.menuBar.tools.menu add command -label "Statistics for fit" -command {

	    toplevel .trecStat
	    wm title .trecStat "Statistics for Trec fit"
	    
	    frame .trecStat.frame1

	    if {![info exists trecfitlist]} {
		label .trecStat.label -text "No statistics found."
		pack .trecStat.label -in .trecStat.frame1 -side top -fill x -pady 2m
	    } else {
		for {set i 0} {$i<[llength $trecfitlist]} {incr i} {
		    label .trecStat.label$i \
		        -text "Segment:$i Trec:[format %.4f [lindex $trecfitlist $i]] Sigma:[format %.4f [lindex $trecsigmafitlist $i]]"
		    pack .trecStat.label$i -in .trecStat.frame1 -side top -fill x -pady 2m
		}
	    }

	    button .trecStat.ok -text "OK" -command {destroy .trecStat}

	    pack .trecStat.frame1 .trecStat.ok -in .trecStat -side top -fill x -pady 1m
	}
    }
}

    
# ------------------------------------------------------------------------------------
# The following 2 procedures check what LO and polarization that currently is in use.
# This information is stored in the variables number_of_LO and number_of_pol. The user
# is only allowed to update the .rxg files if both these variables have the value 1.
# ------------------------------------------------------------------------------------


proc checkLO {} {
    global dataMatrix number_of_datalines LOFirstlist LOSecondlist LOTypelist number_of_LO LOType
    set number_of_LO 0
    set j -1
    foreach LO $LOFirstlist {
	incr j
	set type [lindex $LOTypelist $j]
	if {$type=="fixed"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,inUse)==1 && ($dataMatrix($i,LO)==$LO || \
		        $dataMatrix($i,LO)==[lindex $LOSecondlist $j])} {
		    incr number_of_LO
		    set righttype "fixed"
		    break
		}
	    }
	} elseif {$type=="range"} {
	    for {set i 1} {$i < $number_of_datalines} {incr i} {
		if {$dataMatrix($i,inUse)==1 && ($dataMatrix($i,LO)>=$LO && \
		        $dataMatrix($i,LO)<=[lindex $LOSecondlist $j])} {
		    incr number_of_LO
		    set righttype "range"
		    break
		}
	    }
	}
    }
    if {$number_of_LO==1} {
	set LOType $righttype
    }
}

proc checkPol {} {
    global dataMatrix number_of_datalines number_of_pol
    global leftfreqArray rightfreqArray leftfreqlist rightfreqlist
    set number_of_pol 0
    foreach freq $leftfreqlist {
	if {$leftfreqArray($freq)==1} {
	    incr number_of_pol
	    break
	}
    }
    foreach freq $rightfreqlist {
	if {$rightfreqArray($freq)==1} {
	    incr number_of_pol
	    break
	}
    }
}

# ----------------------------------------------------------------------------------------------------
# This procedure distinguishes between the three types of fitting for Gain vs. Elevation.
# This information is stored in the variable "choice". 
# 1 = Adjust for new DPFU, assume TCal(K) and Gain are ok.
# 2 = Fit for both Gain Curve and DPFU. Select also type of gain curve, ELEV or ALTAZ.
# 3 = Adjust TCal(K) to make data lie on existing curve, assuming TCal(K) is wrong by a scale factor.
# ----------------------------------------------------------------------------------------------------

proc outputFit choice {
    global number_of_datalines dataMatrix polydeg currentRXG avgdpfu coefflist gc avgtcal
    global currentPol gctype rchi fgc opacityCurveCorrect
    set DPFU 1
    set k 1
    set dpfucount 0
    set tcalcount 0
    set totaldpfu 0
    set totaltcal 0
    set fileID [open $currentRXG r]
    while {-1 != [gets $fileID line]} {
	if {[string index $line 0] != "\*"} {
	    if {$k==4} {
		split $line
		if {[llength $line] > 1} {
		    if {[lindex $line 0]==$currentPol} {set right 0}
		    if {[lindex $line 1]==$currentPol} {set right 1}
		} else {
		    set right -1
		}
	    }
	    if {$k==5} {
		split $line
		if {$right==-1} {
		    set DPFU [lindex $line 0]
		} else {
		    set DPFU [lindex $line $right]
		}
	    }
	    if {$k==6} {
		split $line
		if {![info exists polydeg]} {
		    if {[lindex $line [expr [llength $line]-1]]=="opacity_correct"} {
		        set polydeg [expr [llength $line]-4]
		        set opacityCurveCorrect 1
		    } else {
		        set polydeg [expr [llength $line]-3]
		        set opacityCurveCorrect 0
		    }
		    set gctype [lindex $line 0]
		}
		set coefflist [lrange $line 2 end]
	    }
	    incr k
	}
    }
    switch $choice {
	1 {
	    for {set i 1} {$i<$number_of_datalines} {incr i} {
		set y 0
		if {$dataMatrix($i,inUse)==1 && $dataMatrix($i,Gain)>0} {
		    set x $dataMatrix($i,Elevation)
		    for {set j 0} {$j<[llength $coefflist]} {incr j} {
		        set y [expr $y+[lindex $coefflist $j]*pow($x,$j)]
		    }
		    set totaldpfu [expr $totaldpfu+double($dataMatrix($i,Gain))/$y]
		    incr dpfucount
		} 
	    }
	    set avgdpfu [format %.4f [expr double($totaldpfu)/$dpfucount]]
	    set fgc 1
	    drawPoly $avgdpfu $coefflist fittedgaincurve $gctype dash red
	    set DPFU $avgdpfu
	}
	2 {
	    set fileID [open $currentRXG r]
	    while {-1 != [gets $fileID line]} {
		if {[string index $line 0] != "\*"} {
		    if {$k==6} {
		        split $line
		        if {[lindex $line [expr [llength $line]-1]]=="opacity_correct"} {
		            set polydeg [expr [llength $line]-4]
		        } else {
		            set polydeg [expr [llength $line]-3]
		        }
		    }
		    incr k
		}
	    }
	    close $fileID
	    
	    toplevel .polynomChoice
	    wm title .polynomChoice "Polynomial degree choice"

	    frame .polynomChoice.frame1
	    frame .polynomChoice.frame2
	    frame .polynomChoice.frame20
	    frame .polynomChoice.frame3

	    label .polynomChoice.header -text \
		"Please select degree of polynomial\nto which the points are to be fitted"
	    entry .polynomChoice.entry -width 3 -textvariable polydeg
	    label .polynomChoice.header2 -text "Please select type of gain curve"

	    radiobutton .polynomChoice.radio1 -text "ELEV" -variable gctype -value ELEV
	    radiobutton .polynomChoice.radio2 -text "ALTAZ" -variable gctype -value ALTAZ

	    button .polynomChoice.ok -text "OK" -command {fitToGainCurve;destroy .polynomChoice}
	    button .polynomChoice.cancel -text "Cancel" -command {destroy .polynomChoice}

	    pack .polynomChoice.header .polynomChoice.entry -in .polynomChoice.frame1 -side left -fill x -padx 3m
	    pack .polynomChoice.radio1 .polynomChoice.radio2 -in .polynomChoice.frame20 -side top -fill x -pady 2m
	    pack .polynomChoice.ok .polynomChoice.cancel -in .polynomChoice.frame3 -side left -anchor center -padx 4m
	    pack .polynomChoice.header2 .polynomChoice.frame20 -in .polynomChoice.frame2 -side left -fill x -padx 3m
	    pack .polynomChoice.frame1 -in .polynomChoice -side top -fill x -pady 1m
	    pack .polynomChoice.frame2 -in .polynomChoice -side top -fill x -pady 3m
	    pack .polynomChoice.frame3 -in .polynomChoice -side top -fill x
	}
	3 {
	    for {set i 1} {$i<$number_of_datalines} {incr i} {
		set y 0
		if {$dataMatrix($i,inUse)==1} {
		    set x $dataMatrix($i,Elevation)
		    for {set j 0} {$j<[llength $coefflist]} {incr j} {
		        set y [expr $y+[lindex $coefflist $j]*pow($x,$j)]
		    }
		    set totaltcal [expr $totaltcal+double($dataMatrix($i,Gain))/($DPFU*$y)]
		    incr tcalcount
		}
	    }
	    set avgtcal [format %.4f [expr double($totaltcal)/$tcalcount]]
	    set statusMessage "TCal table will be scaled by a factor of $avgtcal. To apply this change, update the working file."
	}
    }
    if {[info exists rchi] && [info exists DPFU] && [info exists coefflist]} {
	.menuBar.tools.menu delete 5 last
	.menuBar.tools.menu add command -label "RMS/DPFU: [format %.6f [expr double($rchi)/$DPFU]]"
	.menuBar.tools.menu add separator
	.menuBar.tools.menu add command -label "DPFU: $DPFU"
	.menuBar.tools.menu add separator
	.menuBar.tools.menu add command -label "Coefficients"
	foreach el $coefflist {
	    .menuBar.tools.menu add command -label "$el"
	}
    }
}

# ----------------------------------------------------------------------------------------------
# This procedure is called upon the user selecting the second option in the procedure above. It
# uses an external program, "gnfit", and recieves the Gain Curve, the DPFU and the RMS from this
# program. It also displays the coefficients on the "Tools" menu.
# ----------------------------------------------------------------------------------------------

proc fitToGainCurve {} {
    global number_of_datalines dataMatrix currentInputFitFile currentOutputFitFile currentPol
    global gc polydeg currentRXG coefflist DPFU steps rchi gctype fgc
    global statusMessage
    set fgc 0
    set err -1
    set outFile [open $currentInputFitFile w+]
    exec chmod a+rw $currentInputFitFile
    puts $outFile "*Gain curve type, Degree of polynomial"
    puts $outFile "[expr $polydeg+1] $gctype"
    puts $outFile "*Gain Elevation"
    for {set i 1} {$i<$number_of_datalines} {incr i} {
	if {$dataMatrix($i,inUse)==1 && $dataMatrix($i,Gain)>0} {
	    puts $outFile "$dataMatrix($i,Gain) $dataMatrix($i,Elevation)"
	}
    }
    close $outFile
    catch {set err [exec gnfit $currentInputFitFile $currentOutputFitFile]} catcher
    if {$err != 0 && $err != ""} {
	if {$catcher!=0} {
	    set fileID [open $currentOutputFitFile r]
	    while {-1 != [gets $fileID line]} {
		set err [lindex [split $line] end]
	    }
	    close $fileID
	    if {$err==-15} {
		set statusMessage "The degree of the selected polynomial exceeds the number of points"
	    } else {
		set statusMessage "There was an error in the fit, errorcode $err"
	    }
	} else {
	    set statusMessage "There was an error in the fit, errorcode $err"
	}
    } else {
	set fileID [open $currentOutputFitFile r]
	while {-1 != [gets $fileID line]} {
	    split line
	    set steps [lindex $line 1]
	    set rchi [lindex $line 3]
	    set DPFU [lindex $line 5]
	    set coefflist [lrange $line 7 end]
	}
	close $fileID
	drawPoly $DPFU $coefflist fittedgaincurve $gctype dash red
	set fgc 1
    }
    if {[info exists rchi] && [info exists DPFU] && [info exists coefflist]} {
	.menuBar.tools.menu delete 5 last
	.menuBar.tools.menu add command -label "RMS/DPFU: [format %.6f [expr double($rchi)/$DPFU]]"
	.menuBar.tools.menu add separator
	.menuBar.tools.menu add command -label "DPFU: $DPFU"
	.menuBar.tools.menu add separator
	.menuBar.tools.menu add command -label "Coefficients"
	foreach el $coefflist {
	    .menuBar.tools.menu add command -label "$el"
	}
    }
}

# ------------------------------------------------------------------------------------
# This procedure updates the .rxg file in accordance to the selected fitting options.
# 1 = Only the DPFU is updated.
# 2 = The gain curve and the DPFU is both updated.
# 3 = The Tcal(K) vs. Frequency table is scaled by the correct factor.
# ------------------------------------------------------------------------------------
	
proc updateRXGwithfit choice {
    global currentPol currentRXG coefflist DPFU steps rchi currentOutputFile newfile_filename tempRXG controlFileDir
    global avgdpfu timeinseconds number_of_datalines dataMatrix avgtcal writeflag gctype editedlist pid fgc gc
    global opacityFlag
    if {[lsearch $currentRXG $editedlist]==-1} {
	lappend editedlist $currentRXG
    }
    set writeflag 1
    set fgc 0
    set gc 0
    .c delete gaincurve
    .c delete fittedgaincurve
    switch $choice {
	1 {
	    set tempFile [open $tempRXG w]
	    exec chmod a+rw $tempRXG
	    set fileID [open $currentRXG r]
	    set k 1
	    while {-1 != [gets $fileID line]} {
		if {[string index $line 0] != "\*"} {
		    if {$k==2} {
		        set t [clock seconds]
		        set line "[clock format $t -format %Y] [clock format $t -format %m] [clock format $t -format %d]"
		        puts $tempFile $line
		    } elseif {$k==4} {
		        split $line
		        if {[llength $line] > 1} {
		            if {[lindex $line 0]==$currentPol} {set right 0}
		            if {[lindex $line 1]==$currentPol} {set right 1}
		        } else {
		            set right -1
		        }
		        puts $tempFile $line
		    } elseif {$k==5} {
		        split $line
		        if {$right==-1} {
		            puts $tempFile $avgdpfu
		        } elseif {$right==0} {
		            puts $tempFile "$avgdpfu [lindex $line 1]"
		        } elseif {$right==1} {
		            puts $tempFile "[lindex $line 0] $avgdpfu"
		        }
		    } else {
		        puts $tempFile $line
		    }
		    incr k
		} else {
		    puts $tempFile $line
		}                     
	    }
	    close $fileID
	    close $tempFile
	    exec cp $tempRXG $currentRXG
	    exec rm -f $tempRXG
	    #pid is used to force gndat to take the right "work" file instead of the original rxg file
	    set currentOutputFile [exec gndat $newfile_filename $currentOutputFile $pid $controlFileDir]
	    readData $currentOutputFile
	}
	2 {
	    set tempFile [open $tempRXG w]
	    exec chmod a+rw $tempRXG
	    set fileID [open $currentRXG r]
	    set k 1
	    while {-1 != [gets $fileID line]} {
		if {[string index $line 0] != "\*"} {
		    if {$k==2} {
		        set t [clock seconds]
		        set line "[clock format $t -format %Y] [clock format $t -format %m] [clock format $t -format %d]"
		        puts $tempFile $line
		    } elseif {$k==4} {
		        split $line
		        if {[llength $line] > 1} {
		            if {[lindex $line 0]==$currentPol} {set right 0}
		            if {[lindex $line 1]==$currentPol} {set right 1}
		            puts $tempFile $line
		        } else {
		            set right -1
		            puts $tempFile $line
		        }
		    } elseif {$k==5} {
		        split $line
		        if {$right==-1} {
		            puts $tempFile $DPFU
		        }
		        if {$right==0} {
		            puts $tempFile "$DPFU [lindex $line 1]"
		        }
		        if {$right==1} {
		            puts $tempFile "[lindex $line 0] $DPFU"
		        }
		    } elseif {$k==6} {
		        split $line
		        if {$opacityFlag==1} {
		            puts $tempFile "$gctype [lindex $line 1] $coefflist opacity_corrected"
		        } else {
		            puts $tempFile "$gctype [lindex $line 1] $coefflist"
		        }
		    } else {
		        puts $tempFile $line
		    }
		    incr k
		} else {
		    puts $tempFile $line
		}
	    }
	    close $fileID
	    close $tempFile
	    exec cp $tempRXG $currentRXG
	    exec rm -f $tempRXG
	    set currentOutputFile [exec gndat $newfile_filename $currentOutputFile $pid $controlFileDir]
	    readData $currentOutputFile
	}
	3 {
	    set tempFile [open $tempRXG w]
	    exec chmod a+rw $tempRXG
	    set fileID [open $currentRXG r]
	    set k 1
	    set finish 0
	    while {-1 != [gets $fileID line]} {
		if {[string index $line 0] != "\*"} {
		    if {$line=="end_tcal_table"} {
		        set finish 1
		    }
		    if {$k==2} {
		        set t [clock seconds]
		        set line "[clock format $t -format %Y] [clock format $t -format %m] [clock format $t -format %d]"
		        puts $tempFile $line
		    } elseif {$k>=7 && $finish==0} {
		        split $line
		        if {[lindex $line 0]==$currentPol} {
		            puts $tempFile "[lrange $line 0 1] [format %.4f [expr [lindex $line 2]/$avgtcal]]"
		        } else {
		            puts $tempFile $line
		        }
		    } else {
		        puts $tempFile $line
		    }
		    incr k
		} else {
		    puts $tempFile $line
		}                     
	    }
	    close $fileID
	    close $tempFile
	    exec cp $tempRXG $currentRXG
	    exec rm -f $tempRXG
	    set currentOutputFile [exec gndat $newfile_filename $currentOutputFile $pid $controlFileDir]
	    readData $currentOutputFile
	    replot
	}
    }
}        

#MC:AO *
# ---------------------------------------------------------------------------------------
# This procedure takes the average or the median of the TCal at the different frequencies
# end puts them into the calTableFrequency and calTableTemperature lists.
# @param select if 1 it computes the average, if 2 it computes the median
# ---------------------------------------------------------------------------------------
proc fitForTCal select {
    global currentPol leftfreqlist rightfreqlist dataMatrix number_of_datalines tck pixelx pixely pointoffplot
    global globalxmin globalxmax globalymin globalymax BADVALUE ftck
    #MC:AO
    global calTableFrequency calTableTemperature statusMessage text_ready
    #end
    set ftck 1
    .c delete fittedtcalcurve
    set tc "TCal(K)"
    #MC:AO
    #set tlist {}
    #set flist {}
    set calTableTemperature {}
    set calTableFrequency {}
    #end 
    if {$currentPol=="lcp"} {
	set sortedlist [lsort -real $leftfreqlist]
    }
    if {$currentPol=="rcp"} {
	set sortedlist [lsort -real $rightfreqlist]
    }
    foreach freq $sortedlist {
	set totalTC 0
	set number_of_times 0
	set alltclist {}
	for {set i 1} {$i<$number_of_datalines} {incr i} {
	    if {$dataMatrix($i,Frequency)==$freq && $dataMatrix($i,inUse)==1} {
		if {$dataMatrix($i,$tc)>=0} {
		    set totalTC [expr $totalTC+$dataMatrix($i,$tc)]
		    incr number_of_times
		    lappend alltclist $dataMatrix($i,$tc)
		}
	    }
	}
	#computes average
	if {$select==1} { 
	    if {$number_of_times!=0} {
		set currentTC [format %.4f [expr double($totalTC)/$number_of_times]]
		#MC:AO
		#lappend tlist $currentTC
		#lappend flist $freq
		lappend calTableFrequency $freq
		lappend calTableTemperature $currentTC
		#end
	    }
	#computes median
	} elseif {$select==2} {
	    if {$number_of_times!=0} {
		set alltclist [lsort -real $alltclist]
		if {[expr [llength $alltclist]%2]==0} {
		    set low [lindex $alltclist [expr ([llength $alltclist]/2)-1]]
		    set high [lindex $alltclist [expr ([llength $alltclist]/2)]]
		    set currentTC [format %.4f [expr ($high+$low)/2]]
		} else {
		    set currentTC [format %.4f [lindex $alltclist [expr int(ceil([llength $alltclist]/2))]]]
		}
		#MC:AO
		#lappend tlist $currentTC
		#lappend flist $freq
		lappend calTableFrequency $freq
		lappend calTableTemperature $currentTC
		#end
	    }
	}
    } 
    #MC:AO
    #set xlist $flist
    #set ylist $tlist
    set xlist $calTableFrequency
    set ylist $calTableTemperature
    #end
    foreach fr $calTableFrequency { 
	set i [lsearch $calTableFrequency $fr]
	if {[lindex $xlist $i]<$globalxmin || [lindex $xlist [expr $i+1]]>$globalxmax} {
	} elseif {[lindex $ylist [expr $i+1]]>=$globalymin && \
		[lindex $ylist [expr $i+1]]<=$globalymax} {
	    drawTCalCurve [lindex $xlist $i] [lindex $ylist $i] [lindex $xlist [expr $i+1]] [lindex $ylist [expr $i+1]] \
		fittedtcalcurve dash
	}
    }
    set statusMessage $text_ready
}


proc fitForTrec {} {
    global sourcelist timelist timeAndSourceMatrix number_of_LO dataMatrix number_of_datalines timeinseconds size
    global hourint minvalue maxvalue currentInputFitFile currentOutputFitFile statusMessage tatm trecmark trecfitlist
    global globalymin globalymax pixelx pixely xoffset yoffset pointoffplot avgtrec fittedtrecmark trecmarkerlist
    global trecsigmafitlist hasScaled
    .c delete treccurve
    .c delete fittedtrecmarker
    .c delete fittedtrecmarkaverage
    set secint [expr $hourint*3600]
    min Time
    max Time
    set timemin $minvalue
    set timemax $maxvalue
    time2sec $timemin
    set realtimemin $timeinseconds
    time2sec $timemax
    set realtimemax $timeinseconds
    set range [expr $realtimemax-$realtimemin]
    set err -1
    set trecmarkerlist {}
    set trecfitlist {}
    set taufitlist {}
    set trecsigmafitlist {}
    for {set j 0} {$j<[expr ceil($range/$secint)]} {incr j} {
	    set outFile [open $currentInputFitFile w+]
	exec chmod a+rw $currentInputFitFile
	puts $outFile "*Five arguments"
	puts $outFile "*(# of parameters) (fit type) (trec inital) (tau inital) (Tatm)"
	puts $outFile "2 tau 0.0 0.0 $tatm"
	puts $outFile "*(Tsys-Tspill) Airmass"
	for {set i 1} {$i<$number_of_datalines} {incr i} {
	    if {$dataMatrix($i,inUse)==1 && $dataMatrix($i,Clicked)==1 && \
		    $dataMatrix($i,Realtime)>=[expr $realtimemin+$j*$secint] && \
		    $dataMatrix($i,Realtime)<=[expr $realtimemin+($j+1)*$secint]} {
		set tsys $dataMatrix($i,Tsys)
		set trec $dataMatrix($i,Trec)
		set tspill $dataMatrix($i,Tspill)
		set airmass $dataMatrix($i,Airmass)
		if {$tsys>0 && $airmass>0} {
		    puts $outFile "[expr $tsys-$tspill] $airmass"
		}
	    }
	}
	close $outFile
	catch {set err [exec gnfit $currentInputFitFile $currentOutputFitFile]} catcher
	 if {$err != 0 && $err != ""} {
	     if {$catcher!=0} {
		 set fileID [open $currentOutputFitFile r]
		 while {-1 != [gets $fileID line]} {
		     set err [lindex [split $line] end]
		 }
		 close $fileID
		set statusMessage "There was an error in the fit, errorcode $err"
	     } else {
		 set statusMessage "There was an error in the fit, errorcode $err"
	     }
	 } else {
	    set fileID [open $currentOutputFitFile r]
	     while {-1 != [gets $fileID line]} {
		split line
		set steps [lindex $line 1]
		set rchi [lindex $line 3]
		set trec [lindex $line 5]
		set tau [lindex $line 7]
		set trecsigma [lindex $line 9]
	     }
	    if {$steps>0 && [catch {set dummy [expr int($trec)]}]==0 && [catch {set dummy [expr int($tau)]}]==0} {
		close $fileID
		lappend trecfitlist $trec
		lappend taufitlist $tau
		lappend trecsigmafitlist $trecsigma
		drawTrecCurve $trec $tau $tatm treccurve
		set r 4
		toPixels 0 $trec
		set x $pixelx
		set y $pixely
		if {$trec>=$globalymin && $trec <=$globalymax && $trec!=0} {
		    .c create oval [expr $x-$r] [expr $y-$r] [expr $x+$r] [expr $y+$r] \
		            -fill white -tags trecmarker$j -width 1
		} elseif {$trec>$globalymax} {
		    .c create oval [expr $x-$r] [expr $yoffset-$r-$pointoffplot] \
		            [expr $x+$r] [expr $yoffset+$r-$pointoffplot] -fill white -tags trecmarker$j -width 1
		} elseif {$trec<$globalymin} {
		    .c create oval [expr $x-$r] [expr $size*180+$yoffset-$r+$pointoffplot] [expr $x+$r] \
		            [expr $size*180+$yoffset+$r+$pointoffplot] -fill white -tags trecmarker$j -width 1
		}
		.c addtag fittedtrecmarker withtag trecmarker$j
	    }
	    lappend trecmarkerlist 1
	}
    }
    set trecmin [lindex [lsort -real $trecfitlist] 0]
    set trecmax [lindex [lsort -real $trecfitlist] [expr [llength $trecfitlist]-1]]
    if {$trecmin<$globalymin || $trecmax>$globalymax} {
	if {$trecmin<$globalymin} {
	    set globalymin [expr 0.98*$trecmin]
	} 
	if {$trecmax>$globalymax} {
	    set globalymax [expr 1.02*$trecmax]
	}
	set hasScaled 1
	replot
	set j 0
	foreach trec $trecfitlist {
	    set tau [lindex $taufitlist [lsearch $trecfitlist $trec]]
	    drawTrecCurve $trec $tau $tatm treccurve
	    set r 4
	    toPixels 0 $trec
	    set x $pixelx
	    set y $pixely
	    if {$trec!=0} {
		.c create oval [expr $x-$r] [expr $y-$r] [expr $x+$r] [expr $y+$r] \
		    -fill white -tags trecmarker$j -width 1
	    }
	    .c addtag fittedtrecmarker withtag trecmarker$j
	    incr j
	}
    }
    if {[llength $trecfitlist]>0} {
	set sum 0
	set sigmasum 0
	for {set i 0} {$i<[llength $trecfitlist]} {incr i} {
	    set sum [expr $sum+[lindex $trecfitlist $i]/pow([lindex $trecsigmafitlist $i],2)]
	    set sigmasum [expr $sigmasum+1/pow([lindex $trecsigmafitlist $i],2)]
	}
	set avgtrec [format %.3f [expr $sum/$sigmasum]]
	if {$avgtrec>=$globalymin && $avgtrec <=$globalymax && $avgtrec!=0} {
	    set r 4
	    toPixels 0 $avgtrec
	    set x $pixelx
	    set y $pixely
	    .c create oval [expr $x-$r] [expr $y-$r] [expr $x+$r] [expr $y+$r] \
		-fill black -tags fittedtrecmarkaverage -width 1
	    .c create text [expr $x-[string length $avgtrec]*6] $y -text $avgtrec -tags fittedtrecmarkaverage
	    .c create line [expr $xoffset-10] $y [expr $xoffset-$pointoffplot] $y -tags fittedtrecmarkaverage
	    set fittedtrecmark 1
	}
	set statusMessage "Ready."
    }
    .c bind fittedtrecmarker <Button-1>  {
	toggleTrec
    }
}

proc updateRXGwithTrec {trec} {
    global currentRXG writeflag editedlist tempRXG currentOutputFile pid newfile_filename controlFileDir
    set writeflag 1
    set tempFile [open $tempRXG w]
    exec chmod a+rw $tempRXG
    set fileID [open $currentRXG r]
    if {[lsearch $currentRXG $editedlist]==-1} {
	lappend editedlist $currentRXG
    }
    set k 1
    set done 0
    while {-1 != [gets $fileID line]} {
	if {[string index $line 0] != "\*"} {
	    if {$k==2} {
		set t [clock seconds]
		set line "[clock format $t -format %Y] [clock format $t -format %m] [clock format $t -format %d]"
		puts $tempFile $line
	    } elseif {$k >= 7} {
		if {$done==1} {
		    puts $tempFile [format %.4f $trec]
		} else {
		    puts $tempFile $line
		}
	    } else {
		puts $tempFile $line
	    }
	    set done 0
	    if {$line=="end_tcal_table"} {
		set done 1
	    }
	    incr k
	} else {
	    puts $tempFile $line
	}
    }
    close $fileID
    close $tempFile
    exec cp $tempRXG $currentRXG
    exec rm -f $tempRXG
    set currentOutputFile [exec gndat $newfile_filename $currentOutputFile $pid $controlFileDir]
    if {$currentOutputFile==-1} {
	set statusMessage "There's a problem with the .rxg files. Please check the $controlFileDir directory."
    } else {
	.c delete points
	.c delete sourcetext
	.c delete fittedtcalcurve
	.c delete tcalcurve
	readData $currentOutputFile
	replot
	.menuBar.tools.menu invoke *file
    }
}

# -------------------------------------------------------------------------------------------
# This procedure creates the window that shows the user some details of what information that
# will be used when updating the .rxg file. This and the following procedure updates the tcal
# vs. frequency part of the .rxg file.
# -------------------------------------------------------------------------------------------

proc updateRXGwithTCal {} {
    global sourcelist timelist timeAndSourceMatrix number_of_LO dataMatrix number_of_datalines
    global currentSource currentTime currentPol currentFreq currentTimes 
    #MC:AO added to avoid to update the file if not Tcal fit has been done!
    global calTableFrequency statusMessage
    if {[llength $calTableFrequency]==0} {
	set statusMessage "Please, fit for Tcal first!"
	return
    }
    #end
    if {[info exists currentFreq]==0} {
	set currentFreq "Unknown"
    }
    if {$number_of_LO==1} {
	for {set i 1} {$i<$number_of_datalines} {incr i} {
	    if {$dataMatrix($i,inUse)==1} {
		set currentFreq $dataMatrix($i,LO)
		break
	    }
	}
    }
    set currentTimes {}
    foreach source $sourcelist {
	foreach time $timelist {
	    if {$timeAndSourceMatrix($time,$source)==1} {
		set currentSource $source
		lappend currentTimes $time
	    }
	}
    }
    if {[llength $currentTimes]==1} {
	set currentTime [lindex $currentTimes 0]
    } else {
	set currentTime "Multiple"
    }    

    destroy .rxgWindow

    toplevel .rxgWindow
    
    wm title .rxgWindow "Update working file"
    
    frame .rxgWindow.textFrame
    frame .rxgWindow.leftFrame
    frame .rxgWindow.rightFrame
    frame .rxgWindow.buttonFrame
    
    label .rxgWindow.sourceLabel -text "Current Source:"
    label .rxgWindow.currentSource -width 22 -text $currentSource
    label .rxgWindow.timeLabel -text "Current Time:"
    label .rxgWindow.currentTime -width 22 -text $currentTime
    label .rxgWindow.polLabel -text "Current Polarization:"
    label .rxgWindow.currentPol -width 3 -text $currentPol
    label .rxgWindow.freqLabel -text "Current LO:"
    label .rxgWindow.currentFreq -width 4 -text $currentFreq
    
    button .rxgWindow.buttonFrame.ok -text "Ok" -command {printTCalToRXG; destroy .rxgWindow}
    button .rxgWindow.buttonFrame.cancel -text "Cancel" -command {destroy .rxgWindow}
    #MC:AO deleted because it is not used
    #button .rxgWindow.buttonFrame.time -text "All times" -command {set currentTime All}
    # end MC:AO
    pack .rxgWindow.timeLabel .rxgWindow.sourceLabel .rxgWindow.polLabel .rxgWindow.freqLabel \
	    -in .rxgWindow.leftFrame -side top -fill x -anchor w
    pack .rxgWindow.currentTime .rxgWindow.currentSource .rxgWindow.currentPol .rxgWindow.currentFreq \
	    -in .rxgWindow.rightFrame -side top -fill x -anchor e
    pack .rxgWindow.buttonFrame.ok -in .rxgWindow.buttonFrame -side left -fill x -anchor sw -padx .7c
    pack .rxgWindow.buttonFrame.cancel -in .rxgWindow.buttonFrame -side right -fill x -anchor se -padx .7c
    pack .rxgWindow.leftFrame .rxgWindow.rightFrame -in .rxgWindow.textFrame -side left -fill x
    pack .rxgWindow.textFrame .rxgWindow.buttonFrame -in .rxgWindow -side top -fill x
}

#MC:AO *
# ----------------------------------------------------------------------------------------------------
# This procedure does the actual updating of the .rxg file when updating the tcal vs. frequency table.
# ----------------------------------------------------------------------------------------------------
proc printTCalToRXG {} {
    global currentRXG currentSource currentPol currentFreq timeinseconds leftfreqlist rightfreqlist
    global dataMatrix number_of_datalines timelist currentTimes writeflag editedlist tck tempRXG currentOutputFile pid
    global newfile_filename controlFileDir statusMessage
    #MC:AO
    global calTableFrequency calTableTemperature TCAL_TABLE_ENDER
    #end
    set tck 0
    set ftck 0
    set writeflag 1
    set tempFile [open $tempRXG w]
    exec chmod a+rw $tempRXG
    set fileID [open $currentRXG r]
    if {[lsearch $currentRXG $editedlist]==-1} {
	lappend editedlist $currentRXG
    }
    set k 1
    set done -1
    set tc "TCal(K)"
    #MC:AO
    #if {$currentPol=="lcp"} {
    #    set sortedlist [lsort -real $leftfreqlist]
    #}
    #if {$currentPol=="rcp"} {
    #    set sortedlist [lsort -real $rightfreqlist]
    #}
    #end
    while {-1 != [gets $fileID line]} {
	if {[string index $line 0] != "\*"} {
	    if {$k==2} {
		set t [clock seconds]
		set line "[clock format $t -format %Y] [clock format $t -format %m] [clock format $t -format %d]"
		puts $tempFile $line
	    } elseif {$k>=7} {
		if {[string range $line 0 2]==$currentPol} {
		    if {$done==-1} {set done 0}
		    split $line
		    if {[lindex $line 1]<[lindex $calTableFrequency 0]} {
		        puts $tempFile $line
		    } elseif {[lindex $line 1]>[lindex $calTableFrequency end] && $done==1} {
		        puts $tempFile $line
		    } else {
		        if {$done==0} {
		            #MC:AO this was a bug, Tcal table was written always as it was computed with
		            #an average. Fixed.
		            set i 0
		            foreach freq $calTableFrequency {
		            #foreach freq $sortedlist 
		                set Temperature [lindex $calTableTemperature $i]
		                incr i
		                #set totalTC 0
		                #set number_of_times 0
		                #for {set i 1} {$i<$number_of_datalines} {incr i} {
		                #    if {$dataMatrix($i,Frequency)==$freq && $dataMatrix($i,inUse)==1 && \
		                #            $dataMatrix($i,$tc) > 0} {
		                #        set totalTC [expr $totalTC+$dataMatrix($i,$tc)]
		                #        incr number_of_times
		                #    }
		                #}
		                #if {$number_of_times!=0} {
		                #    set currentTC [format %.4f [expr double($totalTC)/$number_of_times]]
		                #    puts $tempFile "$currentPol $freq $currentTC"
		                #}
		                puts $tempFile "$currentPol $freq $Temperature" 
		            }
		            if {[lindex $line 1]>[lindex $calTableFrequency end]} {
		                puts $tempFile $line
		            }
		            #end
		            set done 1
		        }
		    }
		#MC:AO added to correct a bug: if all previous entries of the Tcal table were not between 
		# the frequency bounds of current Tcal table, then the new entires were not written to file
		} elseif {$done==0} {
		        set i 0
		        foreach freq $calTableFrequency {
		            set Temperature [lindex $calTableTemperature $i]
		            incr i
		            puts $tempFile "$currentPol $freq $Temperature" 
		        }
		        set done 1
		        # write the end_tcal_table marker
		        puts $tempFile $line
		 #end 
		} else {
		    puts $tempFile $line
		}
	    } else {
		puts $tempFile $line
	    }
	    incr k
	} else {
	    puts $tempFile $line
	}
    }
    close $fileID
    close $tempFile
    exec cp $tempRXG $currentRXG
    exec rm -f $tempRXG
    set currentOutputFile [exec gndat $newfile_filename $currentOutputFile $pid $controlFileDir]
    if {$currentOutputFile==-1} {
	set statusMessage "There's a problem with the .rxg files. Please check the $controlFileDir directory."
    } else {
	.c delete points
	.c delete sourcetext
	.c delete fittedtcalcurve
	.c delete tcalcurve
	readData $currentOutputFile
	replot
	.menuBar.tools.menu invoke *file
    }
}    


# ==========================================================================
#
#                           PREFERENCES SECTION
#
# ==========================================================================

proc changePrefs {} {
    global current_DefaultDir pref_DefaultDir currentOutputFile pref_Output
    global currentInputFitFile pref_InputFit currentOutputFitFile pref_OutputFit
    global current_TEMP pref_TEMP controlFileDir pref_controlFileDir
    set pref_DefaultDir $current_DefaultDir
    set pref_controlFileDir $controlFileDir
    set pref_Output $currentOutputFile
    set pref_InputFit $currentInputFitFile
    set pref_OutputFit $currentOutputFitFile
    set pref_TEMP $current_TEMP
    create_prefWindow
}

proc pref_OK {} {
    global current_DefaultDir pref_DefaultDir currentOutputFile pref_Output newfile_filename
    global currentInputFitFile pref_InputFit currentOutputFitFile pref_OutputFit
    global current_TEMP pref_TEMP text_ready controlFileDir pref_controlFileDir statusMessage
    set current_DefaultDir $pref_DefaultDir
    if {$controlFileDir!=$pref_controlFileDir && $controlFileDir!=[string trimright $pref_controlFileDir "/"] && \
	    ![info exists newfile_filename]} {
	set change 1
	set currentOutputFile \
		[exec gndat $newfile_filename $currentOutputFile 0 [string trimright $pref_controlFileDir "/"]]
	if {$currentOutputFile==-1} {
	    set statusMessage "There's a problem with the .rxg files. Please check the $controlFileDir directory"
	    update 
	} else {
	    .c delete points
	    .c delete sourcetext
	    clearScreen
	    readData $currentOutputFile
	    replot
	}
    }
    set controlFileDir [string trimright $pref_controlFileDir "/"]
    if {[catch [exec cp $currentOutputFile $pref_Output]]!=0} {
    }
    set currentOutputFile $pref_Output
    #exec rm -f $currentOutputFile
    set currentInputFitFile $pref_InputFit
    set currentOutputFitFile $pref_OutputFit
    set current_TEMP $pref_TEMP
    destroy .pref
    set statusMessage $text_ready
}

# Create all the graphical widgets for the preferences window
# -----------------------------------------------------------

proc create_prefWindow {} {
    global text_title_preferences

    toplevel .pref

    wm title .pref $text_title_preferences

    frame .pref.frame1 -borderwidth 4 -relief groove
    frame .pref.frame2 -borderwidth 4 -relief groove
    frame .pref.frame3 -borderwidth 4 -relief groove
    frame .pref.frame4
    frame .pref.subframe11
    frame .pref.subframe12
    frame .pref.subframe21
    frame .pref.subframe22
    frame .pref.subframe31
    frame .pref.subframe32

    label .pref.labelDefaultDir -anchor w -width 35 -text "Default directory for FS log files:"
    label .pref.labelControlDir -anchor w -width 35 -text "Default directory for .rxg files:"
    label .pref.labelOutput -anchor w -width 35 -text "Output file for gndat.............:"
    label .pref.labelInputFit -anchor w -width 35 -text "Input file for gnfit..............:"
    label .pref.labelOutputFit -anchor w -width 35 -text "Output file for gnfit.............:"
    label .pref.labelTEMP -anchor w -width 35 -text "Temporary file for gnplt..........:"
	
    entry .pref.entryDefaultDir -width 38 -relief sunken -textvariable pref_DefaultDir
    entry .pref.entryControlDir -width 38 -relief sunken -textvariable pref_controlFileDir
    entry .pref.entryOutput -width 38 -relief sunken -textvariable pref_Output
    entry .pref.entryInputFit -width 38 -relief sunken -textvariable pref_InputFit
    entry .pref.entryOutputFit -width 38 -relief sunken -textvariable pref_OutputFit
    entry .pref.entryTEMP -width 38 -relief sunken -textvariable pref_TEMP

    button .pref.buttonOK -text "Ok" -width 10 -command pref_OK
    button .pref.buttonCancel -text "Cancel" -width 10 -command {destroy .pref}

# Pack Tk widgets for the preferences window
# ------------------------------------------
    
    pack .pref.frame1 -fill x -padx 8m -pady 4m -in .pref
    pack .pref.frame2 -fill x -padx 8m -pady 4m -in .pref
    pack .pref.frame3 -fill x -padx 8m -pady 4m -in .pref
    pack .pref.frame4 -padx 8m -pady 4m -side bottom -in .pref

    pack .pref.subframe11 .pref.subframe12 -side left -in .pref.frame1
    pack .pref.subframe21 .pref.subframe22 -side left -in .pref.frame2
    pack .pref.subframe31 .pref.subframe32 -side left -in .pref.frame3
    
    pack .pref.labelDefaultDir .pref.labelControlDir .pref.labelOutput -in .pref.subframe11 -padx 2m -pady 2m
    pack .pref.entryDefaultDir .pref.entryControlDir .pref.entryOutput -in .pref.subframe12 -padx 2m -pady 2m

    pack .pref.labelInputFit .pref.labelOutputFit -anchor w -padx 2m -pady 2m -in .pref.subframe21
    pack .pref.entryInputFit .pref.entryOutputFit -in .pref.subframe22 -padx 2m -pady 2m

    pack .pref.labelTEMP -in .pref.subframe31 -padx 2m -pady 2m
    pack .pref.entryTEMP -in .pref.subframe32 -padx 2m -pady 2m

    pack .pref.buttonOK .pref.buttonCancel -padx 3m -pady 3m -side left -in .pref.frame4

}

# ==========================================================================
#
#                               PRINT SECTION
#
# ==========================================================================

# ------------------------------
# Print menu selection procedure
# ------------------------------

proc printPlot {} {
    global print_filename print_destination print_default_filename
    set print_filename $print_default_filename
    create_printWindow
}

# ------------------
# Print OK procedure
# ------------------

proc print_OK {} {
    global print_filename print_destination statusMessage text_printing_wait text_ready
    global print_command current_TEMP
    destroy .print
    set statusMessage $text_printing_wait
    update
    switch $print_destination {
	0 {
	    .c postscript -pagewidth 7.5i -file $current_TEMP
	    switch $print_command {
		0 {exec lpr $current_TEMP}
		1 {exec psprint $current_TEMP}
	    }
	    exec rm -f $current_TEMP
	}
	1 {
	    .c postscript -pagewidth 7.5i -file $print_filename
	}
    }
    set statusMessage $text_ready
}

# ---------------------------------------------------
# Procedure to clear all entry fields in print window
# ---------------------------------------------------

proc print_clearscreen {} {
    global print_filename print_destination
    set print_filename ""
    switch $print_destination {
	0 {focus .print}
	1 {focus .print.entryFilename}
    }
}

# -----------------------------------------------------
# Create all the graphical widgets for the print window
# -----------------------------------------------------

proc create_printWindow {} {
    global text_title_print

    toplevel .print
    
    wm title .print $text_title_print

    frame .print.frame1 -borderwidth 4 -relief groove
    frame .print.subframe11
    frame .print.subframe12
    frame .print.subframe13
    frame .print.frame4
    
    label .print.labelDestination -anchor w -width 14 -text "Destination..:"
    label .print.labelCommand -anchor w -width 14 -text  "Print command:"
    label .print.labelFilename -anchor w -width 14 -text "Filename.....:"

    radiobutton .print.buttonPrinter -text "Printer" \
	    -variable print_destination -value 0 -command \
	    {focus .print; if {$print_command > 1} {incr print_command -2}}
    radiobutton .print.buttonFile -text "File" \
	    -variable print_destination -value 1 -command \
	    {focus .print.entryFilename; if {$print_command < 2} {incr print_command 2}}
    radiobutton .print.buttonLPR -text "lpr" -variable print_command \
	    -value 0 -command {set print_destination 0; focus .print}
    radiobutton .print.buttonPSPRINT -text "psprint" -variable print_command \
	    -value 1 -command {set print_destination 0; focus .print}

    entry .print.entryFilename -width 47 -relief sunken -textvariable print_filename
    
    button .print.buttonOK -text "Print" -width 10 -command print_OK
    button .print.buttonClearscreen -text "Clear" -width 10 -command print_clearscreen
    button .print.buttonCancel -text "Cancel" -width 10 -command {destroy .print}
    
    # Pack Tk widgets for the print window
    # ------------------------------------
    
    pack .print.frame1 -fill x -padx 8m -pady 4m -in .print
    pack .print.frame4 -padx 8m -pady 4m -side bottom -in .print
    
    pack .print.subframe11 .print.subframe12 .print.subframe13 \
	    -anchor w -in .print.frame1

    pack .print.labelDestination .print.buttonPrinter .print.buttonFile \
	    -side left -anchor w -padx 2m -pady 2m -in .print.subframe11

    pack .print.labelCommand .print.buttonLPR .print.buttonPSPRINT \
	    -side left -anchor w -padx 2m -pady 2m -in .print.subframe12

    pack .print.labelFilename .print.entryFilename \
	    -side left -anchor w -padx 2m -pady 2m -in .print.subframe13

    pack .print.buttonOK .print.buttonClearscreen .print.buttonCancel \
	    -padx 3m -pady 3m -side left -in .print.frame4

    bind .print.entryFilename <Return> {focus .print}

    bind .print <Return> {print_OK}
}

proc createShortcutWindow {} {
    toplevel .short

    wm title .short "Shortcut explanations"

    frame .short.frame1 -borderwidth 4 -relief groove
    frame .short.frame2 -borderwidth 4 -relief groove
    frame .short.frame3 -borderwidth 4 -relief groove
    frame .short.subframe11
    frame .short.subframe12
    frame .short.subframe21
    frame .short.subframe22
    frame .short.subframe31
    frame .short.subframe32


    label .short.header1 -anchor center -text "Keyboard shortcuts"
    
    label .short.keyexp1 -anchor w -text "Replot"
    label .short.keyexp2 -anchor w -text "Quit (q)"
    label .short.keyexp3 -anchor w -text "Shows all points currently selected on the edit menu."

    label .short.key1 -anchor w -text "r"
    label .short.key2 -anchor w -text "q"
    label .short.key3 -anchor w -text "s"

    label .short.header2 -anchor center -text "Mouse shortcuts"
    
    label .short.mouse1 -anchor w -text "Button-1 while over point:"
    label .short.mouse2 -anchor w -text "Shift+Button-1 while over point:"
    label .short.mouse3 -anchor w -text "Button-3 while over point:"
    label .short.mouse4 -anchor w -text "Button-1 anywhere else:"
    label .short.mouse5 -anchor w -text "Button-2 anywhere else:"
    label .short.mouse6 -anchor w -text "Button-3 anywhere else:"
    
    label .short.mouseexp1 -anchor w -text "Toggles point on/off."
    label .short.mouseexp2 -anchor w -text "Toggles all points with the same time on/off."
    label .short.mouseexp3 -anchor w -text "Connects the points with the same source and frequency/time."
    label .short.mouseexp4 -anchor w -text "Starts a box for zooming. Drag and release to zoom."
    label .short.mouseexp5 -anchor w -text "Starts a box for editing. All points inside turns on."
    label .short.mouseexp6 -anchor w -text "Starts a box for editing. All points inside turns off."
    
    label .short.header3 -anchor center -text "Color explanations"

    label .short.color1 -anchor w -text "White point" 
    label .short.color2 -anchor w -text "Cyan point" -foreground cyan
    label .short.color3 -anchor w -text "Red point" -foreground red
    label .short.color4 -anchor w -text "Green curve" -foreground green 
    label .short.color5 -anchor w -text "Black curve" -foreground black

    label .short.colorexp1 -anchor w -text "Point on the plot, not deleted"
    label .short.colorexp2 -anchor w -text "Point off the plot, not deleted"
    label .short.colorexp3 -anchor w -text "Point on or off the plot, deleted"
    label .short.colorexp4 -anchor w -text "Curve currently in the .rxg file"
    label .short.colorexp5 -anchor w -text "Curve as result of a fit"

    button .short.ok -text "OK" -command {destroy .short}

    pack .short.keyexp1 .short.keyexp2 .short.keyexp3 -in .short.subframe11 -pady 0.5m -side top 
    pack .short.key1 .short.key2 .short.key3 -in .short.subframe12 -pady 0.5m -side top 
    pack .short.mouse1 .short.mouse2 .short.mouse3 .short.mouse4 .short.mouse5 .short.mouse6 \
	-in .short.subframe21 -pady 0.5m -side top -fill x
    pack .short.mouseexp1 .short.mouseexp2 .short.mouseexp3 .short.mouseexp4 .short.mouseexp5 .short.mouseexp6 \
	-in .short.subframe22 -pady 0.5m -side top -fill x
    pack .short.color1 .short.color2 .short.color3 .short.color4 .short.color5 \
	-in .short.subframe31 -pady 0.5m -side top -fill x
    pack .short.colorexp1 .short.colorexp2 .short.colorexp3 .short.colorexp4 .short.colorexp5 \
	-in .short.subframe32 -pady 0.5m -side top -fill x
    
    
    pack .short.subframe11 .short.subframe12 -in  .short.frame1 -side left -fill y -padx 4m
    pack .short.subframe21 .short.subframe22 -in  .short.frame2 -side left -fill y -padx 4m
    pack .short.subframe31 .short.subframe32 -in  .short.frame3 -side left -fill y -padx 4m

    pack .short.header1 .short.frame1 .short.header2 .short.frame2 .short.header3 .short.frame3 .short.ok \
	-side top -pady 2m 
}

# ==========================================================================
#
#                                EXIT SECTION
#
# ==========================================================================

# -------------------------------------------------------------------------------------------------
# This procedure is run when the user chooses to exit. If the user has updated the .rxg files, the
# two procedures after this one are run.
# -------------------------------------------------------------------------------------------------

proc doExit {} {
    global currentOutputFile currentInputFitFile currentOutputFitFile writeflag editedlist pid LOFilelist
    if {$writeflag==1} {
	createOverwriteWindow
    } else {
	  if {$currentOutputFile!=-1} {
	      exec rm -f $currentOutputFile
	  }
	exec rm -f $currentInputFitFile
	exec rm -f $currentOutputFitFile
	foreach rxgfile $editedlist {
	    exec rm -f $rxgfile   ;#These files are only the working files, and NOT the real ones!
	}
	foreach rxg $LOFilelist {
	    exec rm -f $rxg.work.$pid
	}
	exit
    }
}    

proc createOverwriteWindow {} {
    global pid LOFilelist
    set overWriteText "You have updated the .rxg working files.\n\n Do you want to overwrite the original .rxg files?\n\nThe old information will be stored below the new one, but commented out.\n\nReally overwrite?"
    toplevel .over
    
    wm title .over "Copy working files to original .rxg files?"

    frame .over.frame1 -borderwidth 4 -relief groove
    frame .over.frame4
    
    message .over.message -width 500 -text $overWriteText

    button .over.buttonOK -text "Yes" -width 10 -command {
	if {$currentOutputFile!=-1} {
	    exec rm -f $currentOutputFile
	}
	exec rm -f $currentInputFitFile
	exec rm -f $currentOutputFitFile
	copyRXG
	destroy .over
	exit
    }
    button .over.buttonNo -text "No" -width 10 -command {
	if {$currentOutputFile!=-1} {
	    exec rm -f $currentOutputFile
	}
	exec rm -f $currentInputFitFile
	exec rm -f $currentOutputFitFile
	foreach rxg $LOFilelist {
	    if {[string first $pid $rxg]==-1} {
		exec rm -f $rxg.work.$pid
	    } else {
		exec rm -f $rxg
	    }
	}
	destroy .over
	exit
    }
    button .over.buttonCancel -text "Cancel" -width 10 -command {
	destroy .over
    }

    pack .over.frame1 -fill x -padx 8m -pady 4m -in .over
    pack .over.frame4 -padx 8m -pady 4m -side bottom -in .over
    
    pack .over.message -padx 2m -in .over.frame1

    pack .over.buttonOK .over.buttonNo .over.buttonCancel -padx 3m -pady 3m -side left -in .over.frame4

    focus .over
}
 
proc copyRXG {} {
    global editedlist tempRXG LOFilelist pid
    foreach rxgfile $editedlist {
	set workRXG $rxgfile
	set realRXG [string range $rxgfile 0 [expr [string last .rxg $rxgfile]+3]]
	set tempFile [open $tempRXG w]
	exec chmod a+rw $tempRXG
	set workID [open $workRXG r]
	set k 1
	while {-1 != [gets $workID line]} {
	    puts $tempFile $line
	}
	close $workID
	set realID [open $realRXG r]
	while {-1 != [gets $realID line]} {
	    if {[string index $line 0] != "\*"} {
		puts $tempFile "*$line"
	    } else {
		puts $tempFile $line
	    }
	}
	close $realID
	close $tempFile
	exec cp $tempRXG $realRXG
	exec rm -f $tempRXG
	exec rm -f $workRXG
    }
    foreach rxg $LOFilelist {
	exec rm -f $rxg.work.$pid
    }
}



# ==========================================================================
#
#                           TK WIDGETS SECTION
#
# ==========================================================================


canvas .c -width [expr $size*180+$xoffset+$xrightoffset+50] -height [expr $size*180+$yoffset+$yrightoffset]

frame .subframe2
frame .subframe2a -borderwidth 3 -relief groove
frame .subframe2b -borderwidth 3 -relief groove
frame .subframe20 
frame .subframe200 
frame .subframe201 
frame .subframe202 
frame .subframe21
frame .subframe211 
frame .subframe212
frame .subframe22
frame .subframe221 
frame .subframe222


label .labelLabelPointX -width 10 -anchor w -textvariable XPointLabel
label .labelLabelPointY -width 10 -anchor w -textvariable YPointLabel
label .labelLabelPointSource -width 10 -anchor w -text "Source...:"
label .labelLabelPointFreq -width 10 -anchor w -text "Frequency:"
label .labelLabelPointPol -width 10 -anchor w -text "Polarization:"
label .labelLabelPointAzimuth -width 10 -anchor w -text "Azimuth:"
label .labelLabelPointElevation -width 10 -anchor w -text "Elevation:"
label .labelLabelPointTime -width 10 -anchor w -text "Time.....:"
label .labelLabelDummy1 -width 10 -anchor w

label .labelPointX -width 10 -anchor e -textvariable PointX
label .labelPointY -width 10 -anchor e -textvariable PointY
label .labelPointSource -width 10 -anchor e -textvariable PointSource
label .labelPointFreq -width 10 -anchor e -textvariable PointFreq
label .labelPointPol -width 10 -anchor e -textvariable PointPol
label .labelPointAzimuth -width 10 -anchor e -textvariable PointAzimuth
label .labelPointElevation -width 10 -anchor e -textvariable PointElevation
label .labelPointTime -width 10 -anchor e -textvariable PointTime
label .labelDummy1 -width 10 -anchor e

label .labelLabelSelect -width 15 -anchor w -text "Selected points:"
label .labelLabelInclude -width 15 -anchor w -text "Included points:"
label .labelLabelHighlight -width 15 -anchor w -text "Highlighted points:"
label .labelLabelTotal -width 15 -anchor w -text "Total points:"

label .labelPointSelect -width 6 -anchor e -textvariable pointsSelected
label .labelPointInclude -width 6 -anchor e -textvariable pointsIncluded
label .labelPointHighlight -width 6 -anchor e -textvariable pointsHighlighted
label .labelPointTotal -width 6 -anchor e -textvariable number_of_datalines

# Set up canvas to show coordinate system

.c create rectangle [expr $xoffset-$pointoffplot] [expr $yoffset-$pointoffplot] \
    [expr $size*180+$xoffset+$pointoffplot] [expr $size*180+$yoffset+$pointoffplot]
.c create line [expr $xoffset-10] $yoffset [expr $xoffset-$pointoffplot] $yoffset
.c create line [expr $xoffset] [expr $yoffset-$pointoffplot] $xoffset [expr $yoffset-10]
.c create line [expr $size*90+$xoffset] [expr $yoffset-10] [expr $size*90+$xoffset] [expr $yoffset-$pointoffplot] 
.c create line [expr $size*180+$xoffset] [expr $yoffset-10] [expr $size*180+$xoffset] [expr $yoffset-$pointoffplot]
.c create line [expr $size*180+$xoffset+$pointoffplot] $yoffset [expr $size*180+$xoffset+10] $yoffset
.c create line [expr $size*180+$xoffset+$pointoffplot] [expr $size*90+$yoffset] [expr $size*180+$xoffset+10] \
	[expr $size*90+$yoffset]
.c create line [expr $size*180+$xoffset+10] [expr $size*180+$yoffset] [expr $size*180+$xoffset+$pointoffplot] \
	[expr $size*180+$yoffset]
.c create line [expr $size*180+$xoffset] [expr $size*180+$yoffset+$pointoffplot] [expr $size*180+$xoffset] \
	[expr $size*180+$yoffset+10]
.c create line [expr $size*90+$xoffset] [expr $size*180+$yoffset+$pointoffplot] [expr $size*90+$xoffset] \
	[expr $size*180+$yoffset+10]
.c create line [expr $xoffset-10] [expr $size*180+$yoffset] [expr $xoffset-$pointoffplot] [expr $size*180+$yoffset]
.c create line $xoffset [expr $size*180+$yoffset+$pointoffplot] $xoffset [expr $size*180+$yoffset+10]
.c create line [expr $xoffset-10] [expr $size*90+$yoffset] [expr $xoffset-$pointoffplot] [expr $size*90+$yoffset]
.c create text [expr $size*90+$xoffset] $ytitleoffset -anchor n -tags {title}
.c create text [expr $size*90+$xoffset+200] [expr $ytitleoffset+15] -anchor n -tags {poltext}
.c create text [expr $size*90+$xoffset-130] [expr $ytitleoffset+15] -anchor n -tags {opacityHeader}
.c create text [expr $xoffset+30] [expr $yoffset-15] -anchor se -tags {yaxislabel}
.c create text [expr $size*180+$xoffset-25] [expr $size*180+$yoffset+25] -anchor nw -tags {xaxislabel}
.c create text $xoffset [expr $size*180+$yoffset+10] -anchor nw -tags {text x0}
.c create text [expr $size*90+$xoffset] [expr $size*180+$yoffset+10] -anchor nw -tags {text x1}
.c create text [expr $size*180+$xoffset/2] [expr $size*180+$yoffset+10] -anchor nw -tags {text x2}
.c create text [expr $xoffset-10] [expr $size*180+$yoffset] -anchor se -tags {text y0}
.c create text [expr $xoffset-10] [expr $size*90+$yoffset]  -anchor se -tags {text y1}
.c create text [expr $xoffset-10] $yoffset -anchor se -tags {text y2}

frame .menuBar -relief raised -borderwidth 2

menubutton .menuBar.file -text "File" -underline 0 -menu .menuBar.file.menu
menubutton .menuBar.edit -text "Edit" -underline 0 -menu .menuBar.edit.menu
menubutton .menuBar.xaxis -text "Items (X-axis)" -underline 7 -menu .menuBar.xaxis.menu
menubutton .menuBar.items -text "Items (Y-axis)" -underline 7 -menu .menuBar.items.menu
menubutton .menuBar.source -text "Source" -underline 0 -menu .menuBar.source.menu
menubutton .menuBar.frequ -text "Frequencies" -underline 0 -menu .menuBar.frequ.menu
menubutton .menuBar.tools -text "Tools" -underline 0 -menu .menuBar.tools.menu
menubutton .menuBar.scaling -text "Scaling" -underline 1 -menu .menuBar.scaling.menu
menubutton .menuBar.help -text "Help" -underline 0 -menu .menuBar.help.menu

wm title . $mainTitleText

frame .statusbar -relief raised -borderwidth 2
label .labelStatusMessage -textvariable statusMessage

focus .

# Packing the widgets
# -------------------

pack .statusbar -side bottom -fill x
pack .labelStatusMessage -in .statusbar -padx 2m -side left

pack .menuBar -fill x
pack .menuBar.file .menuBar.edit .menuBar.xaxis .menuBar.items .menuBar.source .menuBar.frequ \
	.menuBar.tools .menuBar.scaling -padx 2m -side left
pack .menuBar.help -padx 2m -side right
pack .c -fill x -side left
pack .subframe2a -side top -in .subframe2 -anchor center
pack .subframe200 -side top -in .subframe2a -anchor center
pack .subframe20 -side top -in .subframe2a -anchor center 
pack .subframe21 -side top -in .subframe2 -pady 2c
pack .subframe2b -side top -in .subframe2 -anchor center
pack .subframe22 -side top -in .subframe2b -anchor center 
pack .subframe201 .subframe202 -side left -in .subframe20 -fill x
pack .subframe211 .subframe212 -side left -in .subframe21
pack .subframe221 .subframe222 -side left -in .subframe22 -fill x
pack .labelLabelPointX .labelLabelPointY .labelLabelPointSource .labelLabelPointFreq .labelLabelPointPol \
    .labelLabelPointAzimuth .labelLabelPointElevation .labelLabelPointTime .labelLabelDummy1 \
    -padx 2m -fill x -in .subframe211
pack .labelPointX .labelPointY .labelPointSource .labelPointFreq .labelPointPol .labelPointAzimuth \
    .labelPointElevation .labelPointTime .labelDummy1 -ipadx 1c -in .subframe212
pack .labelLabelHighlight .labelLabelInclude .labelLabelSelect .labelLabelTotal -padx 2m -fill x -in .subframe221
pack .labelPointHighlight .labelPointInclude .labelPointSelect .labelPointTotal -ipadx 1c -in .subframe222
pack .subframe2 -side right



# Create the menu widgets
# -----------------------

menu .menuBar.file.menu
menu .menuBar.edit.menu
menu .menuBar.xaxis.menu
menu .menuBar.items.menu
menu .menuBar.source.menu
menu .menuBar.frequ.menu
menu .menuBar.tools.menu
menu .menuBar.scaling.menu
menu .menuBar.help.menu

.menuBar.file.menu add command -label "New" -command fileselection_dialog
.menuBar.file.menu add command -label "I/O setup" -command changePrefs
.menuBar.file.menu add separator
.menuBar.file.menu add command -label "Print" -command printPlot
.menuBar.file.menu add separator
.menuBar.file.menu add command -label "Exit" -command {doExit}



foreach xit $xitemlist {
    .menuBar.xaxis.menu add radiobutton -label "$xit" -variable xitem -value "$xit" -command {
	set statusMessage $text_replot
	set scaling Auto
	if {$autoreplot==1} {
	    replot
	    set statusMessage $text_ready
	}
    }
}

.menuBar.scaling.menu add radiobutton -label "Autoscale not including deleted" -variable scaling -value Auto \
	-command {
    set tempList {}
    set autoStyle 0
    set hasScaled 0
    if {[info exists globalxmin]} {
	scale 
	if {$globalxmin!=$globalxmax && $globalymin!=$globalymax} {
	    drawNodes
	} else {
	    set statusMessage $text_zero
	}
    } else {
	set statusMessage "No axes selected."
    }
}

.menuBar.scaling.menu add radiobutton -label "Autoscale including deleted" -variable scaling -value AutoInc \
	-command {
    set autoStyle 1
    set tempList {}
    set hasScaled 0
    if {[info exists globalxmin]} {
	scale 
	if {$globalxmin!=$globalxmax && $globalymin!=$globalymax} {
	    drawNodes
	} else {
	    set statusMessage $text_zero
	}
    } else {
	set statusMessage "No axes selected."
    }
}

.menuBar.scaling.menu add radiobutton -label "Manual" -variable scaling -value Manual -command {set hasScaled 0;scale}

.menuBar.help.menu add command -label "Shortcuts" -command createShortcutWindow
.menuBar.help.menu add command -label "About" -command {
    toplevel .taboutBox 
    wm title .taboutBox "GNPLT about box"
    frame .taboutBox.frame0
    label .taboutBox.infotitle -text "Information about GaiN PLot"
    label .taboutBox.version -text [format "version: %d.%d.%02d" \
	$CurrentProgramVersion $CurrentProgramRelease $CurrentProgramBuild]
    label .taboutBox.descr1 -text "GaiN PLoT is a Field System tool for"
    label .taboutBox.descr2 -text "amplitude calibration of the VLBI telescopes."
    label .taboutBox.descr3 -text "Make sure the TCL/TK 8.4.x is properly installed in your system."
    button .taboutBox.okButton -text "OK" -command {
	destroy .taboutBox
    }
    pack .taboutBox.frame0 -in .taboutBox -anchor center -side top
    pack .taboutBox.infotitle -in .taboutBox.frame0 -anchor center
    pack .taboutBox.version -in .taboutBox.frame0 
    pack .taboutBox.descr1 -in .taboutBox.frame0 
    pack .taboutBox.descr2 -in .taboutBox.frame0 
    pack .taboutBox.descr3 -in .taboutBox.frame0 
    pack .taboutBox.okButton -in .taboutBox.frame0 -side bottom
}

# ---------------------
# Global event bindings
# ---------------------

bind .c <Button-1> {boxBegin %W %x %y}
bind .c <B1-Motion> {boxDrag %W %x %y}
bind .c <ButtonRelease-1> {boxZoom %x %y}

bind .c <Button-2> {boxBegin %W %x %y}
bind .c <B2-Motion> {boxDrag %W %x %y}
bind .c <ButtonRelease-2> {boxChange %x %y 1}

bind .c <Button-3> {boxBegin %W %x %y}
bind .c <B3-Motion> {boxDrag %W %x %y}
bind .c <ButtonRelease-3> {boxChange %x %y 0}

.c bind points <Any-Enter> {
    updatePointData
}

.c bind sourcetext <Any-Enter> {
    updatePointData
}

.c bind points <Any-Leave> {
    clearPointData
}

.c bind sourcetext <Any-Leave> {
    clearPointData
}

.c bind points <Button-1> {
    togglePoint
}

.c bind points <Button-3> {
    .c delete connectCurve
    connect
}

.c bind points <Shift-Button-1> {
    toggleManyPoints
}

#.c bind fittedtrecmarker <Button-1>  {
#    toggleTrec
#}

bind . <KeyPress-s> {
    showAlmostAll
}

bind . <KeyPress-r> {
    replot
}

bind . <KeyPress-q> {
    doExit
}

bind all <Button-1> {
    set currentW %W
}

# ---------------------------------------------------------------------------------------
# This switch procedure allows the user to give additional arguments to the command line.
# ---------------------------------------------------------------------------------------

switch $argc {
    0 {
    }
    1 {
	if {[string index [lindex $argv 0] 0]=="-"} {
	    if {[string index [lindex $argv 0] 1]=="r"} {
		set autoreplot 1
		set xitem "Elevation"
		set items "Gain"
		set gainChoice 1
	    }
	} else {
	    set newfile_filename [lindex $argv 0]
	    set legendNo 1; #makes the source legend be set only once
	    set currentOutputFile [exec gndat [lindex $argv 0] $currentOutputFile 0 $controlFileDir]
	    if {$currentOutputFile==-1} {
		set statusMessage "There's a problem with the .rxg files. Please check the $controlFileDir directory."
	    } else {
		.c delete points
		readData $currentOutputFile
	    }
	}
    }
    2 {
	if {[string index [lindex $argv 0] 1]=="r"} {
	    set autoreplot 1
	    set xitem "Elevation"
	    set items "Gain"
	    set gainChoice 1
	}
	set newfile_filename [lindex $argv 1]
	set legendNo 1           ;#makes the source legend be set only once
	set currentOutputFile [exec gndat [lindex $argv 1] $currentOutputFile 0 $controlFileDir]
	if {$currentOutputFile==-1} {
	    set statusMessage "There's a problem with the .rxg files. Please check the $controlFileDir directory."
	} else {
	    .c delete points
	    readData $currentOutputFile
	}
    }
}

	
    





